The Properties.load would close the InputStream?
Asked Answered
S

3

7

I saw this example, and I didn't see the close() method invoked on the InputStream, so would prop.load() close the stream automatically? Or is there a bug in the example?

Selfinduced answered 17/10, 2016 at 3:36 Comment(2)
I just checked the java code for load(stream) and it doesn't close the stream.Higginbotham
Bug in the example. Properties.load() doesn't close the stream. You have to do that. Very poor quality example all round. It wouldn't even work on some operating systems. Don't rely on arbitrary Internet junk. Use the Oracle Java Tutorials.Nivernais
H
8

The Stream is not closed after Properties.load ()

public static void main(String[] args) throws IOException {

    InputStream in = new FileInputStream(new File("abc.properties"));

    new Properties().load(in);

    System.out.println(in.read());
}

The above code returns "-1" so the stream is not closed. Otherwise it should have thrown java.io.IOException: Stream Closed

Higginbotham answered 17/10, 2016 at 3:52 Comment(0)
M
4

Why do you ask when the javadoc of Properties.load(InputStream inStream) says this?

The specified stream remains open after this method returns.

It has been saying that since Java 6.

As EJP said in a comment: Don't rely on arbitrary Internet junk. Use the official Oracle Java documentation as your primary source of information.

Mauriac answered 17/10, 2016 at 4:13 Comment(0)
C
1

The following try-with-resources will close the InputStream automatically (you can add catch and finally if needed):

try (InputStream is = new FileInputStream("properties.txt")) {
    // is will be closed automatically
}

Any resource declared within a try block opening will be closed. Hence, the new construct shields you from having to pair try blocks with corresponding finally blocks that are dedicated to proper resource management.

Article by Oracle here: http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html.

Cirrate answered 2/8, 2018 at 8:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.