Converting a Filename to a URL


A file object is used to a give a filename. Creating the File object doesn't mean that a file exists. It may be that the does not exist. Suppose if the file exists, first of all we need to convert the file object in URL, for this we use a method toURL(). It returns a URL object and throws MalformedException. After this we will convert this URL to a file object by using getFile() method. We will read this file by using BufferedReader object.
toURL() : It is used to convert the file name into the URL.
getFile() : This is the method of the URL class, is used to get the file name from the URL.
Here is the code of the program:

import java.io.*;
import java.net.*;

public class ConstructFileNamePath{
  public static void main(String[] args){
    File file=new File("C:/work/chandan/deepak.txt");
    URL url=null;
    try{
      //The file may or may not exist
      url=file.toURL();   //file:/C:/work/chandan/deepak.txt
      System.out.println("The url is" + url);

      // change the URL to a file object
      file=new File(url.getFile());      // c:/work/chandan/deepak.txt
      System.out.println("The file name is " + file);
      int i;
    
      //opens an input stream
      InputStream is=url.openStream();
      BufferedReader br=new BufferedReader(new InputStreamReader(is));
      do{
        i=br.read();
        System.out.println((char)i);
      }while (i!=-1);
      is.close();
    }
    catch (MalformedURLException e){
      System.out.println("Don't worry,exception has been caught" + e);
    }
    catch (IOException e){
      System.out.println(e.getMessage());
    }  
  }
}