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:


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 = != -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 ="");
	} catch (Exception e) {

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

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

The output will be:" typ

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


URL (Java Platform SE 7 )

Recent Comments