Is there any harm in failing to close a file when a Java program terminates?
<p>When my program starts, it opens a file and writes to it periodically. (It's not a log file; it's one of the outputs of the program.) I need to have the file available for the length of the program, but I don't need to do anything in particular to end the file; just close it.</p>

<p>I gather that for file I/O in Java I'm supposed to implement <code>AutoCloseable</code> and wrap it in a try-with-resources block. However, because this file is long-lived, and it's one of a few outputs of the program, I'm finding it hard to organize things such that all the files I open are wrapped in try-with-resources blocks. Furthermore, the top-level classes (where my <code>main()</code> function lies) don't know about this file.</p>

<p>Here's my code; note the lack of <code>writer.close()</code>:</p>

<pre><code>public class WorkRecorder {

    public WorkRecorder(String recorderFile) throws FileNotFoundException {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(recorderFile)));
    }

    private Writer writer;

    public void record(Data data) throws Exception {

        // format Data object to match expected file format
        // ...

        writer.write(event.toString());
        writer.write(System.lineSeparator());
        writer.flush();
    }
}
</code></pre>

<p><strong>tl;dr</strong> do I need to implement <code>AutoCloseable</code> and call <code>writer.close()</code> if the resource is an opened output file, and I never need to close it until the program is done? Can I assume the JVM and the OS (Linux) will clean things up for me automatically?</p>

<p>Bonus (?): I struggled with this in C#'s <code>IDisposeable</code> too. The <code>using</code> block, like Java's try-with-resources construct, is a nice feature when I have something that I'm going to open, do something with quickly, and close right away. But often that's not the case, particularly with files, when the access to that resource hangs around for a while, or when needing to manage multiple such resources. If the answer to my question is "always use try-with-resources blocks" I'm stuck again.</p>