Explain how to read from a remote file when we have its URL
With the help of the following code you could directly read from the URL:
import java.net.*;
import java.io.*;
public class URLReader
{
public static void main(String[] args) throws Exception
{
URL xyz = new URL(http://www.xyz.com/);
BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
In the above program, openStream() gets an input stream on the specified URL. A BufferedReader is then opened on the input stream and the URL is read from the BufferedReader.
Another way to do this is:
import java.net.*;
import java.io.*;
public class URLConnectionReader
{
public static void main(String[] args) throws Exception
{
URL xyz = new URL(http://www. xyz.com/);
URLConnection xyzcon = xyz.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(xyzcon.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Here, a URLConnection object is explicitly retrieved and an input stream is fetched from the connection. The connection is opened implicitly by calling getInputStream. A BufferedReader is created on the input stream and is read from BufferedReader.