Closing Input Streams

As with output streams, input streams should be closed when you're through with them to release any native resources such as file handles or network ports that the stream is holding onto. To close a stream, invoke its close( ) method:

public void close( ) throws IOException

Once you have closed an input stream, you should no longer read from it. Most attempts to do so will throw an IOException (though there are a few exceptions).

Not all streams need to be closedSystem.in generally does not need to be closed, for example. However, streams associated with files and network connections should always be closed when you're done with them. As with output streams, it's best to do this in a finally block to guarantee that the stream is closed, even if an exception is thrown while the stream is open. For example:

// Initialize this to null to keep the compiler from complaining // about uninitialized variables InputStream in = null; try { URL u = new URL("http://www.msf.org/"); in = u.openStream( ); // Read from the stream... } catch (IOException ex) { System.err.println(ex); } finally { if (in != null) { try { in.close( ); } catch (IOException ex) { System.err.println(ex); } } }

If you can propagate any exceptions that are thrown, this strategy can be a little shorter and simpler. For example:

// Initialize this to null to keep the compiler from complaining // about uninitialized variables InputStream in = null; try { URL u = new URL("http://www.msf.org/"); in = u.openStream( ); // Read from the stream... } finally { if (in != null) in.close( ); }

Категории