Do I have to close FileOutputStream which is wrapped by PrintStream?
Asked Answered
M

5

28

I'm using FileOutputStream with PrintStream like this:

class PrintStreamDemo {  
    public static void main(String args[]) { 
        FileOutputStream out; 
        PrintStream ps; // declare a print stream object
        try {
            // Create a new file output stream
            out = new FileOutputStream("myfile.txt");

            // Connect print stream to the output stream
            ps = new PrintStream(out);

            ps.println ("This data is written to a file:");
            System.err.println ("Write successfully");
            ps.close();
        }
        catch (Exception e) {
            System.err.println ("Error in writing to file");
        }
    }
}

I'm closing only the PrintStream. Do I need to also close the FileOutputStream (out.close();)?

Madelynmademoiselle answered 10/11, 2011 at 14:0 Comment(2)
Check out the source code: docjar.com/html/api/java/io/PrintStream.java.htmlGranddaughter
By the way, the beauty of PrintStream is the fact you can use it with just a String (for the filename) or a File object. You do not need to open a FOStream just to use it in the PrintStream.Coupon
S
33

No, you only need to close the outermost stream. It will delegate all the way to the wrapped streams.

However, your code contains one conceptual failure, the close should happen in finally, otherwise it's never closed when the code throws an exception between opening and closing.

E.g.

public static void main(String args[]) throws IOException { 
    PrintStream ps = null;

    try {
        ps = new PrintStream(new FileOutputStream("myfile.txt"));
        ps.println("This data is written to a file:");
        System.out.println("Write successfully");
    } catch (IOException e) {
        System.err.println("Error in writing to file");
        throw e;
    } finally {
        if (ps != null) ps.close();
    }
}

(note that I changed the code to throw the exception so that you understand the reason of the problem, the exception namely contains detailed information about the cause of the problem)

Or, when you're already on Java 7, then you can also make use of ARM (Automatic Resource Management; also known as try-with-resources) so that you don't need to close anything yourself:

public static void main(String args[]) throws IOException { 
    try (PrintStream ps = new PrintStream(new FileOutputStream("myfile.txt"))) {
        ps.println("This data is written to a file:");
        System.out.println("Write successfully");
    } catch (IOException e) {
        System.err.println("Error in writing to file");
        throw e;
    }
}
Shimmer answered 10/11, 2011 at 14:2 Comment(3)
When i add finally block and try to do ps.close() in there i get error: variable ps might not have been initializedMadelynmademoiselle
You need to initialize it with null.Shimmer
Note that I updated the answer with a Java 7 example which is more terse.Shimmer
M
8

No , here is implementation of PrintStream's close() method:

public void close() {
    synchronized (this) {
        if (! closing) {
        closing = true;
        try {
            textOut.close();
            out.close();
        }
        catch (IOException x) {
            trouble = true;
        }
        textOut = null;
        charOut = null;
        out = null;
        }
    }

You can see out.close(); which closes output stream.

Mill answered 10/11, 2011 at 14:3 Comment(0)
V
6

No, according to the javadoc, the close method will close the underlying stream for you.

Valtin answered 10/11, 2011 at 14:2 Comment(0)
C
6

No you dont need to. PrintStream.close method automatically closes the underlining output stream.

Check the API.

http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#close%28%29

Coupon answered 10/11, 2011 at 14:2 Comment(0)
R
-2

No. It is not require to close other components. when you close stream it automatically close other related component.

Rooke answered 10/10, 2018 at 11:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.