JAVA:IO 异常:原因流已关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12470059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:01:49  来源:igfitidea点击:

JAVA: IO Exception: Reason Stream closed

javafileiofilewriterbufferedwriter

提问by Bob

Why am I getting the following exception? What I am doing is writing a giant ArrayList line by line to a file onto the disk. The file generated is about >700MB. It seems like it has some problem when written line by line. Could the size of the file a reason? Why is the stream closed? By the way, I am working on a Windows OS.

为什么我会收到以下异常?我正在做的是将一个巨大的 ArrayList 一行一行地写入磁盘上的文件。生成的文件大约>700MB。一行一行写的时候好像有点问题。文件的大小可能是一个原因吗?为什么流关闭?顺便说一下,我正在使用 Windows 操作系统。

FileWriter evaluated_result = 
    new FileWriter(path_output+this.algorithm+"/"+query_type+"/"+"queries.eval");
BufferedWriter out = new BufferedWriter(evaluated_result);
out.write(Myobject);
out.newLine();
evaluated_result.close();
out.close();

The exception is as follows:

例外情况如下:

java.io.IOException: Stream closed
    at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:45)
    at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:118)
    at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
    at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)
    at java.io.BufferedWriter.close(BufferedWriter.java:264)
    at Assignment_1.Query_Evaluator.write100BestDocumentsEvalFormat(Query_Evaluator.java:85)
    at Assignment_1.Experiment.ConductExperiment(Experiment.java:54)
    at Assignment_1.Main.main(Main.java:78)

回答by Jord?o

You should close the BufferedWriterbeforeclosing the FileWriter.

您应该BufferedWriter关闭FileWriter.

And, the closing calls should be in a finally block. This is one way to do it (with one finally):

并且,结束调用应该在 finally 块中。这是一种方法(最后一种):

FileWriter evaluated_result = new FileWriter(path_output+this.algorithm+"/"+query_type+"/"+"queries.eval");
BufferedWriter out = new BufferedWriter(evaluated_result);
try {
  out.write(Myobject);
  out.newLine();
}
finally {
  if (out != null) out.close();
  if (evaluated_result != null) evaluated_result.close();
}

(Look herefor more options)

(更多选项请看这里

Also note that, as mentioned by @oldrinb, you don't have to close nested streams. But I think it's good practice anyway.

另请注意,正如@oldrinb 所提到的,您不必关闭嵌套流。但我认为无论如何这是一个很好的做法。

With Java 7 you can use the try-with-resourcesstatement.

在 Java 7 中,您可以使用try-with-resources语句。