Java Reference
In-Depth Information
public final InputStream openStream() throws IOException
The openStream() method connects to the resource referenced by the URL , performs
any necessary handshaking between the client and the server, and returns an Input
Stream from which data can be read. The data you get from this InputStream is the raw
(i.e., uninterpreted) content the URL references: ASCII if you're reading an ASCII text
file, raw HTML if you're reading an HTML file, binary image data if you're reading an
image file, and so forth. It does not include any of the HTTP headers or any other
protocol-related information. You can read from this InputStream as you would read
from any other InputStream . For example:
try {
URL u = new URL ( "http://www.lolcats.com" );
InputStream in = u . openStream ();
int c ;
while (( c = in . read ()) != - 1 ) System . out . write ( c );
in . close ();
} catch ( IOException ex ) {
System . err . println ( ex );
}
The preceding code fragment catches an IOException , which also catches the Malfor
medURLException that the URL constructor can throw, since MalformedURLException
subclasses IOException .
As with most network streams, reliably closing the stream takes a bit of effort. In Java
6 and earlier, we use the dispose pattern: declare the stream variable outside the try
block, set it to null, and then close it in the finally block if it's not null. For example:
InputStream in = null
try {
URL u = new URL ( "http://www.lolcats.com" );
in = u . openStream ();
int c ;
while (( c = in . read ()) != - 1 ) System . out . write ( c );
} catch ( IOException ex ) {
System . err . println ( ex );
} finally {
try {
if ( in != null ) {
in . close ();
}
} catch ( IOException ex ) {
// ignore
}
}
Java 7 makes this somewhat cleaner by using a nested try-with-resources statement:
try {
URL u = new URL ( "http://www.lolcats.com" );
Search WWH ::




Custom Search