Explain how to read from a remote file when we have its URL

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.
What is Uniform Resource Identifier (URI)?
What is Uniform Resource Identifier (URI)? - A URI is in the form of a string of characters for the purpose of identifying an abstract or physical resource...
Java URL handling architecture
Java URL handling architecture - Java URL architecture is handled by the java.net.URL object instances. It is utilized to handle the URL string...
Brief about java.net.URL class
java.net.URL class - URL is represented to identify or to point to a resource [a web portal / web page] on the WWW...
Post your comment