6

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?

user207421
  • 305,947
  • 44
  • 307
  • 483
Jason
  • 1,115
  • 14
  • 25
  • 2
    I just checked the java code for load(stream) and it doesn't close the stream. – Lyju I Edwinson Oct 17 '16 at 03:41
  • 2
    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. – user207421 Oct 17 '16 at 03:52

3 Answers3

7

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

Lyju I Edwinson
  • 1,764
  • 20
  • 20
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.

Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

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.