Java Reference
In-Depth Information
no exceptions. It is used when you need to know exactly how many bytes to read or
when you need to create a buffer large enough to hold the data in advance.
As networks get faster and files get bigger, it is actually possible to find resources whose
size exceeds the maximum int value (about 2.1 billion bytes). In this case, getConten
tLength() returns -1. Java 7 adds a getContentLengthLong() method that works just
like getContentLength() except that it returns a long instead of an int and thus can
handle much larger resources:
public int getContentLengthLong() // Java 7
Chapter 5 showed how to use the openStream() method of the URL class to download
text files from an HTTP server. Although in theory you should be able to use the same
method to download a binary file, such as a GIF image or a .class byte code file, in
practice this procedure presents a problem. HTTP servers don't always close the con‐
nection exactly where the data is finished; therefore, you don't know when to stop read‐
ing. To download a binary file, it is more reliable to use a URLConnection 's getConten
tLength() method to find the file's length, then read exactly the number of bytes indi‐
cated. Example 7-3 is a program that uses this technique to save a binary file on a disk.
Example 7-3. Downloading a binary file from a website and saving it to disk
import java.io.* ;
import java.net.* ;
public class BinarySaver {
public static void main ( String [] args ) {
for ( int i = 0 ; i < args . length ; i ++) {
try {
URL root = new URL ( args [ i ]);
saveBinaryFile ( root );
} catch ( MalformedURLException ex ) {
System . err . println ( args [ i ] + " is not URL I understand." );
} catch ( IOException ex ) {
System . err . println ( ex );
}
}
}
public static void saveBinaryFile ( URL u ) throws IOException {
URLConnection uc = u . openConnection ();
String contentType = uc . getContentType ();
int contentLength = uc . getContentLength ();
if ( contentType . startsWith ( "text/" ) || contentLength == - 1 ) {
throw new IOException ( "This is not a binary file." );
}
try ( InputStream raw = uc . getInputStream ()) {
InputStream in = new BufferedInputStream ( raw );
Search WWH ::




Custom Search