How To Read File From URL In Java?

By Faruque Ahamed Mollick

I have already told you how to read a text file that is located in your local directory. We used BufferedReader Java class that is available to use when we import java.io.*

Now in this simple tutorial, we are going to read a file that is available on an URL. Here I am going to show you the Java code which will do this task.

Encoding JSON In Java With Simple Example

Suppose we are going to read a file that is located at the URL http://domain.com/file.txt.

At first, we need to import the Java networking and then Java input output stream. below is the given code to import these:

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

After that, we will create the object of URL class and then we will use BufferedReader Java class. This BufferedReader class I previously used to read a text file from the local directory and here also I am using it to read a file from URL. Here is how we did it – Simple Java Code To Read A File Using BufferedReader.

URL url = new URL("http://domain.com/file.txt");
BufferedReader read = new BufferedReader(
new InputStreamReader(url.openStream()));

 Understanding do-while loop in java language



Complete final Java code to read file from URL

Below is the Java code which will read a file from URL:

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

public class ReadURL {
    public static void main(String[] args) throws Exception {

        URL url = new URL("http://domain.com/file.txt");
        BufferedReader read = new BufferedReader(
        new InputStreamReader(url.openStream()));

        String i;
        while ((i = read.readLine()) != null)
            System.out.println(i);
        read.close();
    }
}

The path of the file in this example is http://domain.com/file.txt and we have passed it into the object of URL class. After that, we read it using BufferedReader class. At the end, we have read the file line by line using a while loop.

Leave a Reply

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