Do I need to close local IO threads in Java?

If the thread was created locally, is it necessary to close it at the end of the method?

public void method() {
    FileInputStream fis = new FileInputStream("input.txt");
    ...
    fis.close(); //Необходимо ли это?
}
Author: NaN, 2019-11-22

3 answers

Yes, you need to close it so that there is no memory leak. When closing, we tell the garbage collector that the object can be cleaned up. If you don't want to close it manually, there is an alternative: try-с-ресурсами:

try (FileInputStream fis = new FileInputStream("input.txt")) {
        //тут что-то делать с fis.
} catch(IOException e) {
        // обработка исключений
} finally {
        // финализация чего-либо
}

FileInputStream it will be closed automatically. In the simplest case, finally can be abandoned altogether.

 1
Author: Leonis, 2019-11-22 15:03:51

Necessarily. When the object is created, it is opened for reading and the system must know when the resource will become free again. Also, if the thread is not closed, a memory leak may occur.

 2
Author: Andrew Grow, 2019-11-22 14:58:50

Leonis case says. Moreover, it is highly recommended to use try-с-ресурсами (for Java 7 and higher) instead of closing manually in the finally {[5 block]}

 1
Author: duck codes, 2019-11-22 15:14:39