The Java io package provides classes and interface for accessing the web pages. You can even access the website pages and download the data.
In this tutorial we are downloading the data from http://www.yahoo.com using our java program and then saving on to our hard disk in a file.
So, with the hop of java program you can download the HTML pages from website and save on disk.
In this example code we have used following classes of java.net package:
a) URL class is used to access the www resource.
b) The we have used the BufferReader class to read the data in buffer
c) Finally retrieved the data in String class and printed on console.
Following is the complete example code in Java which reads the data from website and prints on the console.
/* This program was taken from the Java Tutorial
http://java.sun.com/docs/books/tutorial/networking/urls/readingURL.html
Modified by Fred Swartz to use the Java 1.1 "Reader" classes. 24 Nov 1997
*/
import java.net.*;
import java.io.*;
class ReadURL {
public static void main(String[] args) {
try {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}//end main
}//end class ReadURL
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yahooConnection = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(yaho