Should I close the stream when reusing FileOutputStream?

As indicated in the header, should I close the stream when reusing the FileOutputStream variable? For example, in the following codes, I have to call outfile.close()before assigning a new file to it, 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...");
}
+4
source share
3 answers

, " " FileOutputStream. , , - ( outfile ), . Java. , - FileOutputStream, , . , , - . FileOutputStream, null , .

close . ( , , .) , close IOException, , , , .

+2

. (), . , (), , , ..

Java FileOutputStream.close()

, . .

java.

+5

try-with-resources (. ), :

for (int index = 1; shouldCreateNewFile(); ++index) {
  FileOutputStream outfile = new FileOutputStream(index + ".txt");
  try {
    outfile.write(getNewFileContent());
  }
  finally {
    outfile.close();
  }
}

, Java 7 , . , :

for (int index = 1; shouldCreateNewFile(); ++index) {
  try (FileOutputStream outfile = new FileOutputStream(index + ".txt")) {
    outfile.write(getNewFileContent());
  }
}

The output stream will still be closed, but if trythere is an exception in the block and another when the stream is closed, the exception will be suppressed (associated with the main exception), and will not cause the main exception, as in the previous example.

You should always use automatic resource management in Java 7 or higher.

+2
source

Source: https://habr.com/ru/post/1611689/


All Articles