Reading from a URL
Home ] Up ] Protocols ] Resource Names ] Absolute vs. Relative URLs ] The URL Class ] [ Reading from a URL ] Proxy Settings ]

 

 

The URL class provides a method:

public InputStream openStream()

Remember, however, that if you wish to read text from this stream, you must wrap it inside an InputStreamReader, as we discussed in the I/O section.

Here's an application that makes use of this method to read text from a specified URL:

package networking;

import java.net.URL;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *   Application to read text from a URL
 *   specified in the first command line argument.
 *   (Note that this is NOT a Reader, like BufferedReader.)
 */
public class URLReader
{
  public static void main(String[] args) throws Exception
  {
    if (args.length < 1)
    {
      System.err.println("Usage: java URLRreader <URL-to-read>");
    }
    else
    {
      // Construct a URL from the first argument passed in
      URL url = new URL(args[0]);
      BufferedReader reader = new BufferedReader(
          new InputStreamReader(
          url.openStream() ) );
      try
      {
        String line = null;
        while (true)
        {
          line = reader.readLine();
          if (line == null)
            break;
          System.out.println(line);
        }
      }
      finally
      {
        reader.close();
      }
    }
  }
}

For example, if you pass the URL:

http://www.yahoo.com/

to this application, it will print out something like:

 

The page was last updated February 19, 2008