I know how to write to a file in Java. My question is based around when I should release resources.
If I had a thread which writes the contents of an ArrayList to a file every 2 minutes, how do I deal with the resources for file handling. The file could be read by another program at any point.
Every time I write to a file, do I close the FileOutputStream and PrintWriter after each iteration of the loop, or is it more efficient to keep them open and close them when the thread terminates. Or does this lock the file so it can’t be read by another program?
You should close the file streams when you are finished, and reopen them on your next write (2 minutes is a long enough gap that the overhead of opening / closing is insignficant).
In order to ensure that other programs or threads do not access the file while you are writing, then you should lock it by getting the FileChannel and invoking the lock() method.
E.g.