2011-12-31 118 views
1

我寫了一些代碼來讀取文本文件並返回一個數組,每行存儲在一個元素中。我不能爲我的生活找出爲什麼這不起作用......任何人都可以快速瀏覽一下嗎? System.out.println(行)的輸出;是空的,所以我猜測讀取線路時出現問題,但我看不出爲什麼。順便說一句,我傳遞給它的文件肯定有一些內容!閱讀Java中的文本文件

public InOutSys(String filename) { 
    try { 
     file = new File(filename); 
     br = new BufferedReader(new FileReader(file)); 
     bw = new BufferedWriter(new FileWriter(file)); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 



public String[] readFile() { 

    ArrayList<String> dataList = new ArrayList<String>(); // use ArrayList because it can expand automatically 
    try { 
     String line; 

     // Read in lines of the document until you read a null line 
     do { 
      line = br.readLine(); 
      System.out.println(line); 
      dataList.add(line); 
     } while (line != null && !line.isEmpty()); 
     br.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    // Convert the ArrayList into an Array 
    String[] dataArr = new String[dataList.size()]; 
    dataArr = dataList.toArray(dataArr); 

    // Test 
    for (String s : dataArr) 
     System.out.println(s); 

    return dataArr; // Returns an array containing the separate lines of the 
    // file 
} 
+0

你確定你已經有文件了嗎?你是否在正確的位置查找文件(相對於用戶導演)? – 2011-12-31 13:23:26

+0

file/br/bw在哪裏聲明? InOutSys和readFile是公開的,但第二個關閉br。如何避免在封閉的br上調用readFile? – 2011-12-31 13:38:35

+0

文件的位置。 – javaDisciple 2011-12-31 13:40:29

回答

2

首先,使用新的FileWriter(文件)打開FileReader後打開一個FileWriter,FileWriter以創建模式打開文件。所以在你運行你的程序後它會是一個空文件。

其次,文件中是否有空行?如果是這樣,!line.isEmpty()將終止您的do-while-loop。

1

您對正在讀取的文件使用FileWriter,因此FileWriter會清除文件的內容。不要同時讀寫同一個文件。

另外:

  • 不要以爲文件包含一行。你不應該使用do/while循環,而應該使用while循環;
  • 總是關閉steamed,讀者和作家在一個最後的塊;
  • catch(Exception)是一種不好的做法。只抓住你想要的例外,並且可以處理。否則,讓他們走上堆棧。
0

有你的問題的幾種可能的原因:

  • 的文件路徑不正確
  • 你不應該試圖讀/同時
  • 寫同一個文件它不是這樣的好想法在構造函數中初始化緩衝區,想一想 - 有些方法可能會關閉緩衝區,使其無法用於該方法或其他方法的後續調用
  • 循環條件不正確

最好嘗試這種方法來閱讀:

try { 
    String line = null; 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
    while ((line = br.readLine()) != null) { 
     System.out.println(line); 
     dataList.add(line); 
    } 
} finally { 
    if (br != null) 
     br.close(); 
} 
1

我不知道,如果你正在尋找改善您提供的代碼或只爲「讀文本文件中的Java」的解決方案的一種方式標題說,但如果你正在尋找解決方案,我建議使用Apache Commons io爲你做。來自FileUtilsreadLines方法將按照您的要求進行。

如果你想從一個很好的例子中學習,FileUtils是開源的,所以你可以看看他們如何選擇實現looking at the source