2012-03-23 110 views
0

您好我一直在使用緩衝Reader來嘗試讀取文本文件和打印文本文件有多少行有一個文件。我的代碼是這樣的......閱讀在Java錯誤

File parent = new File("/Desktop/Test Folder"); 
File text = new File(parent, "/text.txt"); 
FileWriter fw; 
FileReader fr; 
BufferedWriter write; 
BufferedReader read; 
if (!parent.exists()) { 
     parent.mkdir(); 
    } 
    try { 
     text.createNewFile(); 
    } catch (Exception ex) { 
     System.err.println("Error creating file"); 
    } 
    try { 
     fw = new FileWriter(text); 
     fr = new FileReader(text); 
     write = new BufferedWriter(fw); 
     read = new BufferedReader(fr); 
    } catch (Exception ex) { 
     System.err.println("Error trying to write or read file"); 
    } 
    System.out.println("Writing to file..."); 
try { 
     write.write("String number one.\n"); 
     write.write("String number two.\n"); 
     List<String> lines = new LinkedList<String>(); 
     String line = read.readLine(); 
     while (line != null) { 
      lines.add(line); 
      line = read.readLine(); 
     } 
     System.out.printf("Number of lines is %d.\n", lines.size()); 
     write.flush(); 
     write.close(); 
    } catch (Exception ex) { 
     System.err.println("Error writing to file"); 
    } 

當我運行這一點,說有在列表行0元素。任何幫助?我在某個地方犯了一個無用的錯誤,還是我使用了錯誤的方法?我是一個業餘愛好者,所以我懷疑這個錯誤是顯而易見的。無論如何,任何人都可以給我一些幫助嗎?

+0

您需要刷新()在輸出之前,你可以從文件中讀取它。 – 2012-03-23 21:45:05

回答

1

你有沒有嘗試readLine()一個前移動writer.flush();電話嗎?

Writer.flush()documentation

沖洗流。如果數據流已將各種write()方法中的任何字符保存在緩衝區中,請將它們立即寫入其預定目標

因此,如果您在刷新之前清空文件,可能是空的!

+0

由於這是問題 – 2012-03-23 21:48:31

0

你應該把作家的沖洗()和close()的實際讀數。你所要做的就是使用該文件作爲管道。這不是你想要做的,我猜。

+0

close()方法調用flush()...所以只是接近需要()。 http://docs.oracle.com/javase/6/docs/api/java/io/OutputStreamWriter.html#close() – Adam 2012-03-23 21:58:30