2017-03-31 47 views
-3
import java.io.*; 
import java.util.*; 
public class stringstore 
{ 
    public static void main(String[] args) 
    { 
     File file = new File("C:\\a.txt"); 
     try 
     { 
      String strIP=""; 
      Scanner sc = new Scanner(file); 
      while(sc.hasNext()) 
      { 
       String line = sc.nextLine(); 
       String str[] = line.split(", "); 
       strIP = str[0]; 
      } 
      System.out.println(strIP); 
     } 
     catch(IOException e) 
     { 
     // work with the errors here 
     } 
    } 
} 

如何從文本文件讀取下一行並顯示它。如何閱讀Java中的文本文件的下一行?

+0

再次 「緊急/儘快」(來源:[鏈接](http://stackoverflow.com/questions/32140476/need-to-store-a- 2d-list-but-not-using-array#comment52170418_32140476)):「你明智的做法是不要在你的帖子中說明這一點,即使它對你來說很緊急,但要意識到它對我們來說並不緊急。因爲它暗示a)海報認爲他的帖子比其他人更重要(並且這不是因爲**這裏的所有**問題都是同等重要的),並且b)海報想要把對來這裏幫助自己的空閒時間的志願者施加壓力。「 – Pshemo

+1

您自己的代碼已經顯示瞭如何使用Scanner的nextLine方法。而且你已經知道如何使用println。那麼困惑在哪裏? –

+1

順便說一句'hasNext()'測試文本中是否有下一個標記(單詞)。如果在最後一個單詞後面會有兩個空行'hasNext()'將返回'false'。改用'hasNextLine()'。 – Pshemo

回答

1

您可以通過逐行讀取文件中的行:

 BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("filename"))); 
     String line = null; 
     while ((line = bufferedReader.readLine()) != null) { 
      System.out.println(line); 
     } 
1

。在你的代碼只有輕微的錯誤。 試試這個。

import java.io.*; 
    import java.util.*; 
    public class stringstore 
{ 
    public static void main(String[] args) 
{ 
    File file = new File("C:\\a.txt"); 
try 
{ 
String strIP=""; 
Scanner sc = new Scanner(file); 
while(sc.hasNext()) 
{ 
    String line = sc.nextLine(); 
    String str[] = line.split(", "); 
    strIP = str[0]; 
System.out.println(strIP); 
} 

} 
catch(IOException e) 
{ 
    // work with the errors here 
} 
    } 
} 

地方循環內的打印語句