Java Reference
In-Depth Information
byte
[]
data
=
new
byte
[
contentLength
];
int
offset
=
0
;
while
(
offset
<
contentLength
)
{
int
bytesRead
=
in
.
read
(
data
,
offset
,
data
.
length
-
offset
);
if
(
bytesRead
==
-
1
)
break
;
offset
+=
bytesRead
;
}
if
(
offset
!=
contentLength
)
{
throw
new
IOException
(
"Only read "
+
offset
+
" bytes; Expected "
+
contentLength
+
" bytes"
);
}
String
filename
=
u
.
getFile
();
filename
=
filename
.
substring
(
filename
.
lastIndexOf
(
'/'
)
+
1
);
try
(
FileOutputStream
fout
=
new
FileOutputStream
(
filename
))
{
fout
.
write
(
data
);
fout
.
flush
();
}
}
}
}
As usual, the
main()
method loops over the URLs entered on the command line, passing
each URL to the
saveBinaryFile()
method.
saveBinaryFile()
opens a
URLConnec
tion
uc
to the
URL
. It puts the type into the variable
contentType
and the content length
into the variable
contentLength
. Next, an
if
statement checks whether the content type
is
text
or the Content-length field is missing or invalid (
contentLength == -1
). If
either of these is
true
, an
IOException
is thrown. If these checks are both
false
, you
have a binary file of known length: that's what you want.
Now that you have a genuine binary file on your hands, you prepare to read it into an
array of bytes called
data
.
data
is initialized to the number of bytes required to hold the
binary object,
contentLength
. Ideally, you would like to fill
data
with a single call to
read()
but you probably won't get all the bytes at once, so the read is placed in a loop.
The number of bytes read up to this point is accumulated into the
offset
variable, which
also keeps track of the location in the
data
array at which to start placing the data
retrieved by the next call to
read()
. The loop continues until
offset
equals or exceeds
contentLength
; that is, the array has been filled with the expected number of bytes. You
also break out of the
while
loop if
read()
returns -1, indicating an unexpected end of
stream. The
offset
variable now contains the total number of bytes read, which should
be equal to the content length. If they are not equal, an error has occurred, so
saveBi
naryFile()
throws an
IOException
. This is the general procedure for reading binary
files from HTTP connections.
Now you're ready to save the data in a file.
saveBinaryFile()
gets the filename from
the URL using the
getFile()
method and strips any path information by calling
file
name.substring(theFile.lastIndexOf(
/
) + 1)
. A new
FileOutputStream fout
is