2012-03-23 111 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