Closing Input Streams

When you’re through with a stream, you should close it. This allows the operating system to free any resources associated with the stream; exactly what these resources are depends on your platform and varies with the type of the stream. However, systems only have finite resources. For example, on most personal computer operating systems, no more than several hundred files can be open at once. Multiuser operating systems have larger limits, but limits nonetheless.

To close a stream, you invoke its close() method:

public void close() throws IOException

Not all streams need to be closed—System.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. For example:

try {
  URL u = new URL("http://www.javasoft.com/");
  InputStream in = u.openStream();
  // Read from the stream...
  in.close();
}
catch (IOException e) {System.err.println(e);}

Once you have closed an input stream, you can no longer read from it. Attempting to do so will throw an IOException.

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.