Java I/O How to - Convert Between a File/Path and a URL








Question

We would like to know how to convert Between a File/Path and a URL.

Answer

/*from   w  ww.  jav a2  s.  c  o m*/
import java.io.File;
import java.io.InputStream;
import java.net.URI;

public class Main {
  public static void main(String[] argv) throws Exception {
    File file = new File("filename");

    URI uri = file.toURI();
    System.out.println(uri);
    file = new File(uri.toURL().getFile());
    InputStream is = uri.toURL().openStream();
    is.close();
  }
}

The code above generates the following result.