• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java URL Class Example | Create, Read and Parse URL

March 25, 2019 by javainterviewpoint Leave a Comment

Java URL Class represents the URL [Uniform Resource Locator], through which you can locate and retrieve data from the network. The URL Class in Java enables us to get the data without the need to worry about the way to communicate with the server, or the protocol which needs to be used during the communication or the format of the message which will be returned.

What is a URL ?

URL stands for Uniform Resource Locator. A URL is nothing more than the address of a given unique resource on the Web, in simple word each valid URL will be pointing a unique resource such a file, HTML page, document etc.

URL has two main components – Protocol and Resource name

Let’s look into the below url

https://www.javainterviewpoint.com/

Protocol : For the above URL the protocol is “https”

Resource name: javainterviewpoint.com will be the Resource Name

Further more the Resource can be split into

Host name : This is the name of the machine where the particular resource exists

Filename: Path of the file where the file in the machine

Port Number: The port to which we need to connect to the server, this mostly optional if the web server uses the standard ports of the HTTP protocol [80 for HTTP and 443 for HTTPS]

URL Class in Java

What is URL class in Java?

The java.net.URL class is a Final Class [Cannot be sub classed] extends java.lang.Object, The URL Class in Java supports many protocols such as “http”, “ftp”, “file”, “mailto”, “gopher” etc…

The URL Class uses a protocol handler to establish a connection with a server and use the protocol which is necessary to retrieve data. For example, an HTTP protocol handler knows how to talk to an HTTP server and retrieve a document, likewise an FTP protocol handler knows how to talk to an FTP server and retrieve a file.

Constructor and Method of URL class

The Java URL Class provides several constructors for creating the URLs.

Constructor Description
URL(String url) throws MalformedURLException This constructor creates the URL object from the specified String
URL(String protocol, String host, int port, String file) throws MalformedURLException This constructor creates the URL object using the specified protocol, host, port number, and file
URL(String protocol, String host, int port, String file, URLStreamHandler handler) This constructor creates the URL object using the specified protocol, host, port number, file, and handler
URL(String protocol, String host, String file) This Constructor creates the URL from the specified protocol, host, and file
URL(URL context, String spec) This Constructors creates the URL by parsing the given spec within the context
URL(URL context, String spec, URLStreamHandler handler) This Constructors creates a URL by parsing the given spec with the specified handler within the context

Some of the important Methods of the URL Class

Methods Description
public String getQuery() This Method gets the query part of the URL
public String getPath() This Method gets the path part of the URL
public String getUserInfo() This Method gets the user information of the URL
public String getAuthority() This Method gets the authority information of the URL
public int getPort() This Method gets the port number of the URL
public int getDefaultPort() This Method gets the default port number of the protocol which is associated with the URL
public String getProtocol() This Method gets the protocol name of the URL
public String getHost() This Method gets host name of the URL, format conforms to RFC 2732
public String getFile() This Method gets the file name of the URL, it will be same as getPath() when there is no query parameter
public String getRef() This Method gets the anchor / reference of the URL

How to Create URL in Java

Creating URL using URL Class is pretty simple, We can simply make use of the URL Class constructors to create a URL. Let’s understand few different ways to create URL objects.

package com.javainterviewpoint;

import java.net.MalformedURLException;
import java.net.URL;

public class CreateURL
{
	public static void main(String[] args)
	{
		try
		{
			// Create a new absolute URL
			URL url1 = new URL ("https://www.javainterviewpoint.com/");
			System.out.println(url1.toString());
			
			// Create a relative URL
			URL url2 = new URL (url1,"/star-pattern-programs-in-java/");
			System.out.println(url2.toString());
			
			// Create URL passing the Protocol, Hostname, Path
			URL url3 = new URL ("https", "www.javainterviewpoint.com", "/star-pattern-programs-in-java/");
			System.out.println(url3.toString());
			
			// Create URL passing the Protocol, Hostname, port number, Path
			URL url4 = new URL ("https", "www.javainterviewpoint.com", 443, "/star-pattern-programs-in-java/");
			System.out.println(url4.toString());
		} 
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
	}
}

This is the easiest way to create a URL, all you need to do is that pass the URL string [absolute URL] of the resource to constructor of the URL class.

URL url1 = new URL (“https://www.javainterviewpoint.com/”);

In the second approach of creating URL, we will be creating a relative URL by passing the path relative to the base URL. The first argument is a URL object that specifies the base URL and the second argument is a String that specifies the resource name relative to the base URL. This approach comes handy when your site has a lot different pages, you can create the URL of the pages relative to the URL of the main site [Base URL].

URL url2 = new URL (url1,”/star-pattern-programs-in-java/”);

If baseURL is null, then the constructor treats relativeURL as an absolute URL and if relative URL is treated as an absolute URL, then the constructor ignores baseURL.

The Third and fourth approach will be useful when you have the entites of the URL such as protocol, host name, filename, port number, and reference components separately. Say for example, if you have a screen which has the options for the users to select the Protocol, port, host etc.. Then we can use the below constructors to build the URL objects.

URL url3 = new URL (“https”, “www.javainterviewpoint.com”, “/star-pattern-programs-in-java/”);

URL url4 = new URL (“https”, “www.javainterviewpoint.com”, 443, “/star-pattern-programs-in-java/”);

How to open and read from a URL in Java

Since we have created the URL using the above approaches, let’s see how to open and read from a URL in Java.

package com.javainterviewpoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class ReadURL
{
	public static void main(String[] args)
	{
		try
		{
			URL url = new URL ("https://www.google.com");
			
			BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( url.openStream()));
			
			String input;
			
			while ((input = bufferedReader.readLine()) != null)
			{
				System.out.println(input);
			}
			bufferedReader.close();
			
		} catch (MalformedURLException me)
		{
			me.printStackTrace();
		} catch (IOException ie)
		{
			ie.printStackTrace();
		}
	}
}
  • Create a new URL object, passing in the URL string which we need to access to the URL class constructor
  • The openStream() method returns InputStream which can be passed to the bufferedReader.
  • Using the BufferedReader’s readLine() method which returns the content of the URL.

How to Read from URL and write to file in Java

let’s see how to read from URL and write to file in Java

package com.javainterviewpoint;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class WriteURL
{
    public static void main(String[] args)
    {
        FileOutputStream fileOutputStream = null;
        BufferedReader bufferedReader = null;
        
        try
        {
            URL url = new URL ("https://www.google.com");
            
            bufferedReader = new BufferedReader( new InputStreamReader( url.openStream()));
            fileOutputStream = new FileOutputStream("D:\\JIP\\test.txt");
            String input;
            
            while ((input = bufferedReader.readLine()) != null)
            {
                System.out.println(input);
                fileOutputStream.write(input.getBytes());
            }
            bufferedReader.close();
            fileOutputStream.close();
            
        } catch (MalformedURLException me)
        {
            me.printStackTrace();
        } catch (IOException ie)
        {
            ie.printStackTrace();
        }
    }
}
  • Create a new URL object and pass the URL of the resource to the constructor.
  • Read the content of the URL using the bufferedReader.
  • The readLine() method of the BufferedReader which reads the content of the URL
  • Write the content to a file using the write() method of the FileOutputStream.

How to Parse URL

Let’s parse URL and get the different components which makes up the URL

package com.javainterviewpoint;

import java.net.MalformedURLException;
import java.net.URL;

public class ParseURL
{
    public static void main(String[] args)
    {
        try
        {
            URL url = new URL ("https://www.google.com/search?q=url+class+in+java#java");
            
            System.out.println("Protocol    : " + url.getProtocol());
            System.out.println("File        : " + url.getFile());
            System.out.println("Host        : " + url.getHost());
            System.out.println("Port        : " + url.getPort());
            System.out.println("Path        : " + url.getPath());
            System.out.println("Query       : " + url.getQuery());
            System.out.println("UserInfo    : " + url.getUserInfo());
            System.out.println("Authority   : " + url.getAuthority());
            System.out.println("DefaultPort : " + url.getDefaultPort());
            System.out.println("Reference   : " + url.getRef());
            
        } catch (MalformedURLException me)
        {
            me.printStackTrace();
        }
    }
}
  • getProtocol() – Returns the name of the protocol used in the URL
  • getFile() – Returns the complete path, including the query  string
  • getHost() – Returns the name of the Host
  • getPort() – Returns the port using in the URL, returns -1 when the port number is not explicitly specified
  • getPath() – Return the path of the URL, excluding the query string
  • getQuery() – Returns the query string of the URL
  • getUserInfo() –  Returns the user information
  • getAuthority() – Returns the authority information of the URL
  • getDefaultPort() – Returns the default port of the URL, example 443 for HTTPS and 80 for HTTP
  • getRef() – Returns the anchor element present in the URL

Output:

Protocol    : https
File        : /search?q=url+class+in+java
Host        : www.google.com
Port        : -1
Path        : /search
Query       : q=url+class+in+java
UserInfo    : null
Authority   : www.google.com
DefaultPort : 443

Other interesting articles which you may like …

  • RSA Encryption and Decryption
  • Java URL Encode and Decode Example
  • Java Salted Password Hashing
  • Google Tink Example – Google Cryptography
  • AES 256 Encryption and Decryption
  • AES 128 Encryption and Decryption
  • Constructor in Java
  • Private Constructors in Java
  • Java Constructor Chaining with example
  • Java – Constructor in an Interface?
  • Constructor.newInstance() method
  • Parameterized Constructor in Java
  • Java 8 – Lambda Expressions
  • Java 8 – ForEach Example
  • Java 8 Default Methods in Interface
  • Multiple Inheritance in Java 8 through Interface
  • Java 9 – jdeprscan
  • Private Methods in Interfaces Java 9
  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword
  • Abstract Class in Java
  • Interface in Java and Uses of Interface in Java
  • What is Marker Interface
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serailization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method

Filed Under: Core Java, Java Tagged With: Create URL, Java URL Class, Parse URL, Read URL, URL Class, URL Class in Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·