Search code examples
javamemory-leaksio

Should I need to close IO streams in Java?


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.


Solution

  • 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