Converting Between a Filename Path and a URL - Java Network

Java examples for Network:URL

Description

Converting Between a Filename Path and a URL

Demo Code

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("filename");
    URL url = null;//  w ww.  j a  va 2  s . c o  m
    try {
      url = file.toURL(); // file:/d:/folder1.4/java.io/filename
    } catch (MalformedURLException e) {
    }
    file = new File(url.getFile()); // d:/folder1.4/java.io/filename
    try {
      InputStream is = url.openStream();

      // Read from is

      is.close();
    } catch (IOException e) {
      // Could not open the file
    }
  }
}

Related Tutorials