2

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.

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)
Vikdor
  • 23,934
  • 10
  • 61
  • 84
Bob
  • 991
  • 8
  • 23
  • 40

1 Answers1

7

You should close the BufferedWriter before closing the FileWriter.

And, the closing calls should be in a finally block. This is one way to do it (with one 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 here for 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.

With Java 7 you can use the try-with-resources statement.

Community
  • 1
  • 1
Jordão
  • 55,340
  • 13
  • 112
  • 144