Reader Example
Home ] Up ] [ Reader Example ] Writer Example ] Extended Example ] Posting Form Data ]

 

 

Here's the equivalent to the URLReader program we developed earlier, but using a URLConnection:

package networking;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

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

/**
 *   Application to read text from a URL specified in the
 *   first command line argument, using a URLConnection
 *   (Note that this is NOT a Reader in the same sense as BufferedReader.)
 */
public class URLConnectionReader
{
  public static void main(String[] args)
  {
    URL url = null;
    BufferedReader reader = null;
    try
    {
      url = new URL(args[0]);
      URLConnection conn = url.openConnection();
      reader = new BufferedReader(
                    new InputStreamReader(
                          conn.getInputStream()));
      String line = null;
      while (true)
      {
        line = reader.readLine();
        if (line == null)
          break;
        System.out.println(line);
      }
    }
    catch (MalformedURLException ex)
    {
      ex.printStackTrace();
    } 
    catch (IOException ex)
    {
      ex.printStackTrace();
    }
    finally
    {
      try
      {
        reader.close();
      }
      catch (IOException ioe)
      {
        // Do nothing here
      }
    }
  }
}
 
The page was last updated February 19, 2008