Java Reference
In-Depth Information
a search-engine company do nothing but browse the internet all day long, look-
ing for new html files, extracting information from new and old files, and saving
this information in a form that allows them to answer queries quickly. Google ,
for example, has 30,000-40,000 computers networked together, not only for
answering your queries but for browsing the internet.
Thus, there is the need to read a file given by a URL. Figure 5.9 gives a
method that you can use in a Java program to read such files. Here is how it
works, assuming that variable url contains a URL :
1. The method call url.openStream() opens a connection to the file given
by URL url . This connection is in the form of an object of class
InputStream , which is stored in variable is .
2. An InputStreamReader isr is created, which can read the file one char-
acter at a time.
3. A BufferedReader is created and returned, which can read one line of the
file at a time.
Suppose this statement is executed:
BufferedReader br= getReader(url);
Then, the lines of the file can be read and processed one at a time, just like the
lines of any other file connected to a BufferedReader . Remember, a line of the
file is read and stored in variable line using
line= br.readLine();
/** = a reader for URL url (which must not be null). If url is null , if the protocol
is not http or file , or if there is an IO error, null is returned. */
public static BufferedReader getReader(URL url) {
if ( url == null )
return null ;
if (!url.getProtocol().equals("http") &&
!url.getProtocol().equals("file")) {
return null ;
try {
InputStream is= url.openStream();
InputStreamReader isr= new InputStreamReader(is);
return new BufferedReader(isr);
} catch (IOException e) {
return null ;
Figure 5.9:
Print two lines on a file chosen by the user
Search WWH ::

Custom Search