Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

A simple Java program to read and download a Web page in a html file

Program to demonstrate how to read and download a webpage in a html file, in Java


public class UrlDownload {

   public static void main(String[] args) {

      try {
 // Create a URL object and pass url as string
 // to download the webpage 
 URL url = new URL("");
 // Create a BufferedReader Object and pass it with
 // InputStreamReader Object containing an InputStream
 // Object retrieved  from openStream() method of URL
 BufferedReader reader = new BufferedReader
                      (new InputStreamReader(url.openStream()));
 // Create a BufferedWriter Object and pass it with
 // FileWriter Object containing an String
 // representing the file name to which 
 // the webpage is to download. 
 BufferedWriter writer = new BufferedWriter
                      (new FileWriter("hubberspot.html"));
 // Create a String object to read each line 
 // one by one from the stream
 String line;
 // looping till there is no line left to download
 while ((line = reader.readLine()) != null) {
 // Writing each line in the document hubberspot.html 
     // to print each line on next line 
 // Closing the BufferedReader and BufferedWriter object 
 // to free the expensive resources
 }// handling two exceptions below 
 // In case URL is malformed MalformedURLException
 // Exception is thrown and 
 // IOException for any input/output failure
    catch (MalformedURLException e) {
   } catch (IOException e) {


Output of the program :

© 2021 Learn Java by Examples Template by Hubberspot