Download web page using Java

Java Program to read and download webpage

Steps:
1. Create a URL object and pass url as string to download the webpage.
URL example = new URL(pass url of webpage you want to download)
2. Create Buffered Reader object and pass openStream(). Method of URL in Input Stream object.
3. Create a string object to read each line one by one from stream.
4. Write each line in html file where webpage will be downloaded.
5. Close all objects.
6. Catch exceptions if url failed to download.

Program:



filter_none

edit
close

play_arrow

link
brightness_4
code

package normal;
// Java program to read and download
// webpage in html file
import java.io.*;
import java.net.URL;
import java.net.MalformedURLException;
  
public class download {
  
    public static void DownloadWebPage(String webpage)
    {
        try {
  
            // Create URL object
            URL url = new URL(webpage);
            BufferedReader readr = 
              new BufferedReader(new InputStreamReader(url.openStream()));
  
            // Enter filename in which you want to download
            BufferedWriter writer = 
              new BufferedWriter(new FileWriter("Download.html"));
              
            // read each line from stream till end
            String line;
            while ((line = readr.readLine()) != null) {
                writer.write(line);
            }
  
            readr.close();
            writer.close();
            System.out.println("Successfully Downloaded.");
        }
  
        // Exceptions
        catch (MalformedURLException mue) {
            System.out.println("Malformed URL Exception raised");
        }
        catch (IOException ie) {
            System.out.println("IOException raised");
        }
    }
    public static void main(String args[])
        throws IOException
    {
        String url = "https://www.geeksforgeeks.org/";
        DownloadWebPage(url);
    }
}

chevron_right


Output:

Successfully Downloaded.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.