0

I'm using OutputStream and InputStream for reading and writing to a .properties file:

try (OutputStream output = new FileOutputStream(path)) {
    // ...
    output.close();
} catch (IOException e) {
    e.printStackTrace();
}

try (InputStream input = new FileInputStream(path)) {
    // ...
    input.close();
} catch (IOException e) {
    e.printStackTrace();
}

But my IDE says those close() calls are redundant. If I don't close them will I have memory leaks? How does that work in Java? Thanks for help.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Bastizlx
  • 23
  • 4
  • 2
    You are using `try-with-resources` statement which ensures that each resource is closed at the end of the statement. So you don't have to do it by yourself. – Madstuffs Oct 14 '19 at 05:10

3 Answers3

8

Using the try-with-resources statement will close the resources automatically, so your close() call is indeed redudant.

You can read more about this topic here

inexcitus
  • 2,471
  • 2
  • 26
  • 41
0

But my IDE says those close() calls are redundant. If I don't close them will I have memory leaks? How does that work in Java?

As you are using try with resources, you do not need to close any resources like OutputStream or InputStream. It will automatically handled by the JVM. there will not memory leaks. How it works. you can refer it here

cpatel
  • 191
  • 4
  • 9
0

In Java, the try-with-resources statement is a try statement that declares one or more resources. The resource is as an object that must be closed after finishing the program. The try-with-resources statement ensures that each resource is closed at the end of the statement execution which will prevent memory leakage.

The Java compiler employs extensive and stringent compile-time checking so that syntax-related errors can be detected early, before a program is deployed. One of the advantages of a strongly typed language (like C++) is that it allows extensive compile-time checking, so bugs can be found early. Also, IDE provide us sufficient information in advance so that we can ensure high quality code.

For more information ,Please visit here.