Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I close stream when reusing FileOutputStream?

As stated in the title, should I close stream when reusing a FileOutputStream variable? For example, in the following codes, should I call the outfile.close() before I assign it a new file and why?

Thanks:)

FileOutputStream outfile = null;
int index = 1;

while (true) {

    // check whether we should create a new file
    boolean createNewFile = shouldCreateNewFile();

    //write to a new file if pattern is identified
    if (createNewFile) {
        /* Should I close the outfile each time I create a new file?
        if (outfile != null) {
            outfile.close();
        }
        */
        outfile = new FileOutputStream(String.valueOf(index++) + ".txt");
    }

    if (outfile != null) {
        outfile.write(getNewFileContent());
    }

    if (shouldEnd()) {
        break;
    }
}

try {
    if (outfile != null) {
        outfile.close();
    }
} catch (IOException e) {
    System.err.println("Something wrong happens...");
}
like image 979
hackjutsu Avatar asked Jan 08 '23 09:01

hackjutsu


1 Answers

YES. Once you are done with one file (stream) you should always close it. So that the resources allocated with the file (stream) will be released to the operating system like file descriptors, buffer etc.

Java Documentation FileOutputStream.close()

Closes this file output stream and releases any system resources associated with this stream. This file output stream may no longer be used for writing bytes.

The unclosed file descriptors can even lead to resource leaks in the java program. Reference

like image 95
YoungHobbit Avatar answered Jan 15 '23 23:01

YoungHobbit