Java Streams  «Prev  Next»
Lesson 6 Closing streams
ObjectiveExamine the importance of closing streams.

Closing Java Stream Data

When you are 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 is platform-dependent and varies with the type of the stream. However, in general 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.
Here is an example of closing a stream associated with a file:

try {
  FileInputStream fis = new FileInputStream("data.txt");
  // read from the stream...
catch (IOException e) {

Input Streams - Quiz

Click on the Quiz link below to take a brief multiple-choice quiz that covers reading streams.
Input Streams - Quiz