Sunday 15 May 2011

Using Java "URL" object to read text and binary data

Just a little example of "URL" object.

To read text data from remote page (for example), use the following piece of code

URL pollingUrl = new URL("http:\\www.google.com");
BufferedReader in
= new BufferedReader(new InputStreamReader( pollingUrl.openStream()));
String inputLine
="";
while (true)
{
inputLine
= in.readLine();
if (inputLine == null)
break;//end of HTML page
}// end while
in.close();
Just open a stream to specific url and use Buffered Reader to read the response, line by line. Very simple. However,
remember that response text is transfered in the html format. So if you need specific information you need to parse it.
Now if you want to download the file to your disk. The idea is the same, just instead of Buffered Reader we use DataInputStream object


FileOutputStream fout = new FileOutputStream("c:\myFile",true);
URL fileURL
= new URL("http://host/myFile.dat");
DataInputStream dis
= new DataInputStream(fileURL.openStream());
int c = dis.read();
while (c != -1 )
{
c
= dis.read(); fout.write(c);
} fout.close();dis.close();
We read bytes from InputStream and in the same time writing it to the disk
 Don't forget to close your streams!!

No comments:

Post a Comment