Java Program To Download A Webpage using Command Line
Learn How To Write a Java Program To Download A Webpage using Command Line Arguments on the Console Screen. This Code To Download a Website Page in Java makes use of Advanced Java Programming concepts. The java.net package plays a very important role in the code.
This Java Code To Fetch the Webpage saves the webpage in an HTML format in a text file. It, therefore, helps you to Save a Webpage for Offline Reading.
How To Enter Command Line Arguments
Syntax
java class_name complete_url file_name
Example
java DownloadWebpage https://www.codingalpha.com CodingAlpha
The First Argument needs to be have the complete URL of the Webpage to be downloaded. It has to even the HTTP or HTTPS. The Second URL is used for saving the webpage in the system. Therefore, you can give it a name along with its extension such as .HTML, .HTM, .TXT and many others. The default extension is .HTML.
Also Read: Java Program To Take User Input using Scanner Class
Code To Download Website in Advanced Java Programming
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | import java.io.*; import java.net.*; public class DownloadWebpage { public static void get(String tURL_String,String tSaveFilename) throws MalformedURLException, IOException { int tByteCount = 0; BufferedInputStream tURL_Input = null; byte tInputByteData[] = new byte[1024]; FileOutputStream tLocalSavedFile = null; try { tURL_Input = new BufferedInputStream(new URL(tURL_String).openStream()); tLocalSavedFile = new FileOutputStream(tSaveFilename); while ((tByteCount = tURL_Input.read(tInputByteData, 0, 1024)) != -1) { tLocalSavedFile.write(tInputByteData, 0, tByteCount); } } catch(MalformedURLException a) { } catch(IOException b) { if (!(tURL_Input == null)) { tURL_Input.close(); } else { throw b; } } if(tLocalSavedFile != null) { tLocalSavedFile.close(); } else { throw new IOException(); } } public static void usage() { System.out.println("Parameters To Download The Webpage: Complete_URL File_Name"); } public static void main(String argument[]) { StringBuilder tStringBuilder = new StringBuilder(240); if(argument.length != 2) { DownloadWebpage.usage(); return; } try { DownloadWebpage.get(argument[0],argument[1]); } catch(Exception c) { c.printStackTrace(); return; } tStringBuilder.append("nThe Webpage is downloaded successfully.nnFile is Saved: ").append(argument[1]); System.out.println(tStringBuilder.toString()); } } |
Also Read: How To Connect C and Java for Java Network Interface
Output

If you have any Compilation Error or Doubt about this Java Program To Download A Webpage, let us know about it in the Comment Section below.
Such an amazing program! Thanks! Now, I can download and save webpages for offline reading! 😀
You’re welcome! I hope this program works on all the websites!