Why do I need to close streams

advertisements

Why do I need to close Streams(FileInputStream etc..)? Does Java is not intelligent to use GC if I didn't close the stream?

public void getLongStrings() throws IOException {
        InputStream i1 = null;
        InputStream i2 = null;
        InputStreamReader isr1 = null;
        InputStreamReader isr2 = null;
        try {
            i1 = aBook.getInputStream();
            i2 = aNovel.getInputStream();
            isr1 = new InputStreamReader(i1);
            isr2 = new InputStreamReader(i2);
            foo = FileCopyUtils.copyToString(isr1);
            bar = FileCopyUtils.copyToString(isr2);
        }
        catch (IOException ioe) {
            //do something appropriate here
        } finally {
            if (i1 != null) i1.close();
            if (i2 != null) i2.close();
            if (isr1 != null) isr1.close();
            if (isr2 != null) isr2.close();
        }
    }

do I need to close all the streams I used?


Garbage collector is meant to collect unused objects. A stream is often linked to a lot of resources (file descriptor, socket, etc...) that are much more critical in your machine. Of course they are likely to be freed on program exit, but they should stay open for as little as possible