Closing Streams

When you're done with a stream, you should close it to release any resources associated with the stream. Once the stream is closed attempts to read from it, will throw IOExceptions.

You close a stream with the close() method:

public void close() throws IOException

An IOException is thrown if the stream can't be closed.

Streams should normally be closed in a finally block to guarantee the release of resources:

InputStream in;
try {
  in = new FileInputStream("data.txt");
  // read from the stream...
}
catch (IOException ex) {
  // handle exceptions...
}
finally {
    if (in != null) {
    try {
      in.close();
    }
    catch (IOException ex) {
      // normally can ignore this
    }
  }
}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 2004, 2005, 2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified August 22, 2006