How to read the content of a URL in Java

This tutorial shows how to read the content of URL in java. It creates a method called read, that takes a String in input and returns the content of the URL. To run the tutorial code and download the file, you need to follow these steps:

1- Create the following java file:

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class ReadUrlContent {
    public String read(String url) throws IOException {

	// Open a stream from the URL
	InputStream is = new URL(url).openStream();

	StringBuilder sb = new StringBuilder();

	int cp;
	while ((cp = is.read()) != -1) {
	    sb.append((char) cp);
	}

	// Return the Object as a String
	return sb.toString();
    }

    public static void main(String[] argv) {
	ReadUrlContent example = new ReadUrlContent();

	// Read the url content.
	String googleContent = "";

	try {
	    googleContent = example.read("http://oliviertech.com/");
	} catch (Exception e) {
	    e.printStackTrace();
	}

	int pos = googleContent.indexOf( "oliviertech" );

	// Show the Content in the output.
	System.out.println(googleContent.substring(pos, pos+20));
    }
}

The output will be:

oliviertech.com" typ

The text returned in the String after the first instance of oliviertech
java read text file from url

References:

URL (Java Platform SE 7 )

Share this article:

Recent Comments