Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Wednesday 4 April 2018

Java program to read and download the web page

In this program i use various predefined API's of java to capture the data from a web page and store it in a separate file in the hard disk.


The Java.io.BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.Following are the important points about BufferedReader −
The buffer size may be specified, or the default size may be used.

Each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.

                                  

The Java.io.BufferedWriter class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.Following are the important points about BufferedWriter − 

The buffer size may be specified, or the default size may be used.

A Writer sends its output immediately to the underlying character or byte stream.


I use the url() keyword here if you want to know more about this keyword then click here


                                EXAMPLE


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
 public static void main(String[] args) 
    throws Exception {
  URL url = new URL("Any website"); //write the website name here in the double quotes
  BufferedReader reader = new BufferedReader
        (new InputStreamReader(url.openStream()));
  BufferedWriter writer = new BufferedWriter
        (new FileWriter("data.html"));
  String line;
  while ((line = reader.readLine()) != null) {
   System.out.println(line);
   writer.write(line);
   writer.newLine();
  }
  reader.close();
  writer.close();
 }
}


1 comment: