0
// Create URL object 
        URL url = new 
               URL("http://tutorials.jenkov.com/javaconcurrency/index.html"); 
        BufferedReader readr =  
          new BufferedReader(new InputStreamReader(url.openStream())); 

        // Enter filename in which you want to download 
        BufferedWriter writer =  
          new BufferedWriter(new FileWriter("C:\\Users\\DELL\\Desktop\\Download.html")); 
          
        // read each line from stream till end 
        String line; 
        while ((line = readr.readLine()) != null) { 
            writer.write(line); 

Main problem is decoding the output that i read using reader.readline()

  • 1
    Please [edit] your question to include the URL you are loading. What exactly do you mean by "decoding"? – Progman Mar 06 '21 at 08:26
  • I want to download webpage using java , so I used FileWrite to write data from inputstream that is return by url.openstream() . data is writed in file now when i open file it is not looking like webpage that I downloaded. – Manjothi Anas Abdul Gani Mar 06 '21 at 19:11
  • 1
    Depending on the content and HTML code of the webpage, there might be other files missing like images or CSS files. Without them the HTML code you downloaded will look differently when viewed in a browser since all the other files are missing. – Progman Mar 06 '21 at 19:13

1 Answers1

1

The java Reader represents a stream of characters and the InputStreamReader converts (wraps) a stream of bytes into a stream of characters. It is imperative for it to use the correct character encoding.

It is certainly possible to do it by parsing the value of url.openConnection().getContentType() (cf. the "Gather HTTP response information" section of this BalusC answer), but in your case it is useless: just read the bytes from the URL and write them to your file, without converting them to chars in the middle:

try (final InputStream is = url.openStream();
     final OutputStream os = new FileOutputStream("C:\\Users\\DELL\\Desktop\\Download.html");) {
    final byte[] buf = new byte[1024];
    int len;
    while ((len = is.read(buf)) != -1) {
        os.write(buf, 0, len);
    }
}
Piotr P. Karwasz
  • 3,213
  • 2
  • 6
  • 17