O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required