Java Reference
In-Depth Information
try
(
InputStream
in
=
u
.
openStream
())
{
int
c
;
while
((
c
=
in
.
read
())
!=
-
1
)
System
.
out
.
write
(
c
);
}
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
Example 5-2
reads a URL from the command line, opens an
InputStream
from that
URL, chains the resulting
InputStream
to an
InputStreamReader
using the default
encoding, and then uses
InputStreamReader
's
read()
method to read successive char‐
acters from the file, each of which is printed on
System.out
. That is, it prints the raw
data located at the URL if the URL references an HTML file; the program's output is raw
HTML.
Example 5-2. Download a web page
import
java.io.*
;
import
java.net.*
;
public
class
SourceViewer
{
public
static
void
main
(
String
[]
args
)
{
if
(
args
.
length
>
0
)
{
InputStream
in
=
null
;
try
{
// Open the URL for reading
URL
u
=
new
URL
(
args
[
0
]);
in
=
u
.
openStream
();
// buffer the input to increase performance
in
=
new
BufferedInputStream
(
in
);
// chain the InputStream to a Reader
Reader
r
=
new
InputStreamReader
(
in
);
int
c
;
while
((
c
=
r
.
read
())
!=
-
1
)
{
System
.
out
.
print
((
char
)
c
);
}
}
catch
(
MalformedURLException
ex
)
{
System
.
err
.
println
(
args
[
0
]
+
" is not a parseable URL"
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
finally
{
if
(
in
!=
null
)
{
try
{
in
.
close
();
}
catch
(
IOException
e
)
{
// ignore
}
}
}
}