External Interfaces/API |
This program, URLdemo
, opens a connection to a web site specified by a URL (Uniform Resource Locator), for the purpose of reading text from a file at that site. It constructs an object of the Java API class, java.net.URL
, which enables convenient handling of URLs. Then, it calls a method on the URL object, to open a connection.
To read and display the lines of text at the site, URLdemo
uses classes from the Java I/O package java.io
. It creates an InputStreamReader
object, and then uses that object to construct a BufferedReader
object. Finally, it calls a method on the BufferedReader
object to read the specified number of lines from the site.
The major tasks performed by URLdemo
are:
1. Construct a URL Object
The example first calls a constructor on java.net.URL
and assigns the resulting object to variable url
. The URL
constructor takes a single argument, the name of the URL to be accessed, as a string. The constructor checks whether the input URL has a valid form.
2. Open a Connection to the URL
The second statement of the example calls the method, openStream
, on the URL
object url
, to establish a connection with the web site named by the object. The method returns an InputStream
object to variable, is
, for reading bytes from the site.
3. Set Up a Buffered Stream Reader
The next two lines create a buffered stream reader for characters. The java.io.InputStreamReader
constructor is called with the input stream is
, to return to variable isr
an object that can read characters. Then, the java.io.BufferedReader
constructor is called with isr
, to return a BufferedReader
object to variable br
. A buffered reader provides for efficient reading of characters, arrays, and lines.
4. Read and Display Lines of Text
The final statements read the initial lines of HTML text from the site, displaying only the first 4 lines that contain meaningful text. Within the MATLAB for
statements, the BufferedReader
method readLine
reads each line of text (terminated by a return
and/or line feed character) from the site.
for k = 1:108 % Skip initial HTML formatting lines s = readLine(br); end for k = 1:4 % Read the first 4 lines of text s = readLine(br) end
Running the Example
When you run this example, you see output similar to the following.
url = http://www.mathworks.com/support/tech-notes/1100/1109.shtml is = ice.net.CachedInputStream@7e700c isr = java.io.InputStreamReader@7e6696 br = java.io.BufferedReader@7e5d1b s = <p class="standard">This technical note provides an introduction to vectorization techniques. s = In order to understand some of the tricks available, an introduction to s = MATLAB indexing is provided. Then several vectorization techniques are s = discussed, in order of simplest to most complicated.
Introduction to Programming Examples | Example - Finding an Internet Protocol Address |