Forgetting to add close() when writing an array to file with Java's PrintWriter, the last part of the array will be left out. Why is that?

StackOverflow https://stackoverflow.com/questions/23490354

  •  16-07-2023
  •  | 
  •  

Question

I noticed something I wasn't aware of when writing an array to file using Java's PrintWriter class. When I forgot to add close() in the end, the last elements of the array weren't printed to the file. Why is that?

Snippets from code:

...
PrintWriter f;
try {
    f = new PrintWriter(new FileWriter("out.txt"));
    for (int i = 0; i < array.length; i++) { // array consists of 5000+ birthnames
        f.println(array[i]);
    }
    f.close(); // Last elements of array will not be printed to out.txt if this line is removed
} catch (IOException e) {
    System.out.println("Exception: " + e);
}
Was it helpful?

Solution

close()

method will close the stream of data, and flushes any data that remains in the pipe to the output. So if you dont call the close() method, the flush is not happening, and the resource is still locked. After the GC runs, it might find the unclosed streams, and it will close it abruptly where you dont have a mechanism to flush the data to output( there is no output!)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top