Dec 29, 2010

How to read content from URL

You can create a stream to read content from regular files.
But if it's an URL, how ?

That's simple, its different with above a little
I will give a small example,

First of all, you need some packages:


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;


Then, you must create an URL you want to refer:

URL url= new URL("http://the link you want");


After you've successfully created a URL object, you can call the URL's openStream() method to get a stream from which you can read the contents of the URL. Still with the object above, I will create a BufferedReader to be able to read content faster:


BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));


Ok, now you can start reading content from URL:
String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
}


Download example code

No comments: