2011-01-19 57 views
-1

好吧,我知道這是一個真正的菜鳥問題,但我環顧四周網上很多,但我無法找到我的問題的答案:如何在java中按行讀取文件中的輸入?

我怎樣才能從一個文件行逐行讀取輸入?

假設對每一行整數文件輸入,如:

1 
2 
3 
4 
5 

這裏的代碼我想與之合作的片段:

public static void main(File fromFile) { 

    BufferedReader reader = new BufferedReader(new FileReader(fromFile)); 

    int x, y; 

    //initialize 
    x = Integer.parseInt(reader.readLine().trim()); 
    y = Integer.parseInt(reader.readLine().trim()); 

} 

據推測,這將在閱讀前兩行並將它們作爲整數存儲在x和y中。因此,舉個例子,x = 1,y = 2。

它發現這個問題,我不知道爲什麼。

+0

你可以發佈任何堆棧strace的? – lweller 2011-01-19 07:32:57

+0

請詳細說明當前代碼的問題是什麼。你有錯誤嗎?這是否僅僅是這個事實,只能讀取2行而不是5行?它不編譯或不運行? – Nanne 2011-01-19 07:33:23

回答

2
public static void main(String[] args) { 
     FileInputStream fstream; 
     DataInputStream in = null; 
     try { 
      // Open the file that is the first 
      // command line parameter 
      fstream = new FileInputStream("textfile.txt"); 
      // Get the object of DataInputStream 
      in = new DataInputStream(fstream); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      String strLine; 
      int x = Integer.parseInt(br.readLine()); 
      int y = Integer.parseInt(br.readLine()); 

      //Close the input stream 

     } catch (Exception e) {//Catch exception if any 
      System.err.println("Error: " + e.getMessage()); 
     } finally { 
      try { 
       in.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

    } 
2

請檢查您的main method()。它應該是這樣的

public static void main(String... args) { 
} 

public static void main(String[] args) { 
} 

然後閱讀這樣的:

BufferedReader reader = new BufferedReader(new FileReader(fromFile)); 

String line; 
while((line = reader.readLine()) != null){ 
     int i = Integer.parseInt(line); 
} 
0

我們通常使用while循環,該readLine方法告訴是否結束文件是否到達:

List<String> lines = new ArrayList<String>(); 
while ((String line = reader.readLine()) != null) 
    lines.add(line); 

現在我們有一個集合(一個列表),它將文件中的所有行保存爲單獨的字符串。


閱讀的內容爲整數,只是定義整數的收集和分析,同時閱讀:

List<Integer> lines = new ArrayList<Integer>(); 
while ((String line = reader.readLine()) != null) { 
    try { 
    lines.add(Integer.parseInt(line.trim())); 
    } catch (NumberFormatException eaten) { 
    // this happens if the content is not parseable (empty line, text, ..) 
    // we simply ignore those lines 
    } 
}