0

Should i close PrintStream only with try/catch/finally blocks or is there another way?

Or is this a bug in the IDE?

public void writeData(String fileDir) throws IOException{

    FileOutputStream fos = new FileOutputStream(fileDir);
    PrintStream ps = new PrintStream(fos);

    for(int i = 0; i < 3; i++) {
        ps.print(stringData[i]);
        ps.print("-");
        ps.print(doubleData[i]);
        ps.print("-");
        ps.print(intData[i]);
        ps.println();

        boolean control = ps.checkError();
        if(control) {
            throw new IOException("IO exception occurred!");
        }
    }

    ps.close();

    System.out.println("Data transfer completed!");

}
Pionix
  • 413
  • 2
  • 8
  • 1
    Use [try with resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). This code does not guarantee to close the stream. – Andy Turner Aug 19 '18 at 20:06
  • 4
    Your code throws an `IOException` on at least one code path. Without a `try-finally` (or `try-with-resources`) you would leave the file handle behind `fos` open. – Elliott Frisch Aug 19 '18 at 20:10

1 Answers1

0

If the control variable is true, a IOException will throws, so, in this case, you never close your PrintStream.

You must close your Streams always in a try-finally block or, if you use java 1.7, in a try-with-resources.

In addition, you have forgotten to close the FileOutputStream too.

try-finally

try {
    FileOutputStream fos = new FileOutputStream(fileDir);
    PrintStream ps = new PrintStream(fos);

    ...

} finally {
     fos.close();
     ps.close();
}

try-with-resources

try (FileOutputStream fos = new FileOutputStream(fileDir); PrintStream ps = new PrintStream(fos)) {

    ....

}
Mar Millán
  • 188
  • 7
  • 1
    Closing the `FileOutputStream` is not necessary here: The `PrintStream` takes ownership and closes the `FileOutputStream` when the `PrintStream` is closed. (Same applies to `Scanner`, which closes `System.in` if it was constructed using that - leading often to other bugs.) – Johannes Kuhn Aug 20 '18 at 00:39