简体   繁体   English

BufferedReader / PrintWriter 有问题吗?

[英]Problems with BufferedReader / PrintWriter?

I'm using BufferedReader and PrintWriter to go through each line of an input file, make a change to some lines, and output the result.我通过输入文件的每一行使用 BufferedReader 和 PrintWriter 到 go,对某些行进行更改,结果为 output。 If a line doesn't undergo a change, it's just printed as is to the output file.如果一行没有发生变化,它就按原样打印到 output 文件中。 For some reason however, the process ends prematurely.然而,出于某种原因,该过程过早结束。 The code looks something like this:代码看起来像这样:

BufferedReader in = new BufferedReader(new FileReader("in.txt"));
FileOutputStream out = new FileOutputStream("out.txt");
PrintWriter p = new PrintWriter(out);
String line = in.readLine();

while(line!=null)
{
   if(line is special)
      do edits and p.println(edited_line);
   else
      p.println(line);

   line = in.readLine();
}

However, for some odd reason, this process ends prematurely (actually prints out a half of a line) towards the very end of my input file.然而,出于某种奇怪的原因,这个过程在我的输入文件的最后提前结束(实际上打印出半行)。 Any obvious reason for this?这有什么明显的原因吗? The while loop is clearly being ended by a null. And it's towards the end of my 250k+ line txt file. while 循环显然由 null 结束。它接近我的 250k+ 行 txt 文件的末尾。 Thanks!谢谢!

Where do you flush/close your PrintWriter or FileOutputStream?您在哪里刷新/关闭 PrintWriter 或 FileOutputStream? If the program exits and this is not done, not all your results will be written out.如果程序退出并且没有完成,则不会写出所有结果。

You need out.close() (possibly a p.flush() as well?) at the end of your process to close the file output stream您需要out.close() (也可能是p.flush()吗?)在流程结束时关闭文件 output stream

Try adding a p.flush() after the loop.尝试在循环后添加一个 p.flush() 。

PrintWriter does not have autoflushing enabled, so its likely that the last bit of the file is not flushed before the program terminates. PrintWriter 没有启用自动刷新,因此在程序终止之前文件的最后一位可能没有刷新。

Adding a p.flush() after your while loop should do the trick.在 while 循环之后添加一个p.flush()应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM