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( );
}


Basic I/O

Introducing I/O

Output Streams

Input Streams

Data Sources

File Streams

Network Streams

Filter Streams

Filter Streams

Print Streams

Data Streams

Streams in Memory

Compressing Streams

JAR Archives

Cryptographic Streams

Object Serialization

New I/O

Buffers

Channels

Nonblocking I/O

The File System

Working with Files

File Dialogs and Choosers

Text

Character Sets and Unicode

Readers and Writers

Formatted I/O with java.text

Devices

The Java Communications API

USB

The J2ME Generic Connection Framework

Bluetooth

Character Sets



Java I/O
Java I/O
ISBN: 0596527500
EAN: 2147483647
Year: 2004
Pages: 244

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net