How to create an URL object in java

This example shows you how to create a URL object in java and read the content of that URL.

Below is the example code of creating URL object and reading the content of that URL.

package com.java.connect.net;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
 
//How to create an URL object in java 
public class NetworkURLExample {
    public static void main(String[] args) {
        try {
 
            // You can create an URL object by passing the
            // full path of url
            URL url = new URL("http://www.java-connect.com/index.html");
 
            // Get the reader to get the content of url
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    url.openStream()));
 
            String text;
            // read each line and print it
            while ((text = reader.readLine()) != null) {
                System.out.println(text);
            }
 
            reader.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

The above example print the content of home page www.java-connect.com.