Java Reference
In-Depth Information
3
public class
ReadFileFromURL {
4
public static void
main(String[] args) {
5 System.out.print(
"Enter a URL: "
);
6
7
8
String URLString =
new
Scanner(System.in).next();
enter a URL
try
{
9
10
java.net.URL url =
new
java.net.URL(URLString);
create a
URL
object
int
count =
0
;
11
12
Scanner input =
new
Scanner(url.openStream());
create a
Scanner
object
more to read?
read a line
while
(input.hasNext()) {
13
14 count += line.length();
15 }
16
17 System.out.println(
"The file size is "
+ count +
" bytes"
);
18 }
19
20 System.out.println(
"Invalid URL"
);
21 }
22
catch
(java.io.IOException ex) {
23 System.out.println(
"I/O Errors: no such file"
);
24 }
25 }
26 }
String line = input.nextLine();
catch
(java.net.MalformedURLException ex) {
MalformedURLException
IOException
Enter a URL:
The file size is 1469 bytes
Enter a URL:
The file size is 190006 bytes
The program prompts the user to enter a URL string (line 6) and creates a
URL
object (line 9).
The constructor will throw a
java.net.MalformedURLException
(line 19) if the URL
isn't formed correctly.
The program creates a
Scanner
object from the input stream for the URL (line 11). If the
URL is formed correctly but does not exist, an
IOException
will be thrown (line 22). For
exist. An
IOException
would be thrown if this URL was used for this program.
MalformedURLException
14.37
How do you create a
Scanner
object for reading text from a URL?
✓
✓
Check
Point
K
EY
T
ERMS
absolute file name
541
exception 518
exception propagation
chained exception
537
527
checked exception
525
relative file name 541
throw exception 526
unchecked exception
declare exception
526
directory path
541
525