Search code examples
javaresource-leakprintstream

Eclipse says PrintStream never closed even though it is closed


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!");

}

Solution

  • 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)) {
    
        ....
    
    }