How to open and read from a URL in Java (with just the URL class)

On this blog I’ve shown several examples of how to read content from a URL using Java. In this example I’d like to show how you can open a URL and read content from that URL by just using the Java URL class.

(In other blog posts I demonstrate how to do something similar using the URLConnection and HttpURLConnection classes. You should be able to find any of these blog posts using the Search box of this blog.)

Source code to open and read a URL in Java

Here’s the source code for a complete Java class that demonstrates how to open a URL and read data from that URL:

import java.net.*;
import java.io.*;

/**
 *
 * A complete Java class that shows how to open a URL, then read data (text) from that URL,
 * just using the URL class, in combination with an InputStreamReader and BufferedReader.
 *
 * @author alvin alexander, devdaily.com.
 *
 */
public class UrlReader
{
  public static void main(String[] args) throws Exception
  {
    String urlString = "http://localhost:8080/";
    
    // create the url
    URL url = new URL(urlString);
    
    // open the url stream, wrap it an a few "readers"
    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

    // write the output to stdout
    String line;
    while ((line = reader.readLine()) != null)
    {
      System.out.println(line);
    }

    // close our reader
    reader.close();
  }
}

As you can see, it doesn’t take many lines of code to read data from a URL. Just create a new URL object, read data from the URL using the openStream method, wrap it in an InputStreamReader and BufferedReader, and loop through the output. How cool — that’s a lot of functionality for less than 10 lines of actual code.