Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Read Directly From a URL Java

There are many ways to get a URL content in Java. Here is the simple example. 

In this example, we use Apache commons IOUtils package to stream read the url content and then use OutputStreamWrite to write to a html file. 

 

 

package com.example.file;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URL;

public class OpenWebPageWithJavaIoUtils {

    public static void main(String[] args) throws IOException {

        //Use Apache Common IOUtils to stream read a web page
        InputStream in = new URL( "http://commons.apache.org" ).openStream();
        //Use Output Stream to create a file
        OutputStream outputStream = new FileOutputStream("temp.html");
        //Write output stream to a file
        Writer writer=new OutputStreamWriter(outputStream);
        try {
            //print out to console
            System.out.println(IOUtils.toString(in));
            //write out to a file
            writer.write(IOUtils.toString(in));
           writer.close();

        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}

Run the code. You will see that http://commons.apache.org page displayed on the console and a file "temp.html" is created with the webpage content. See the partial console content below.

| Generated by Apache Maven Doxia at 09 May 2015
 | Rendered using Apache Maven Fluido Skin 1.3.0