Converting Between a Filename Path and a URL

// Create a file object File file = new File("filename"); // Convert the file object to a URL URL url = null; try { // The file need not exist. It is made into an absolute path // by prefixing the current working directory url = file.toURL(); // file:/d:/almanac1.4/java.io/filename } catch (MalformedURLException e) { } // Convert the URL to a file object file = new File(url.getFile()); // d:/almanac1.4/java.io/filename // Read the file contents using the URL try { // Open an input stream InputStream is = url.openStream(); // Read from is is.close(); } catch (IOException e) { // Could not open the file }

Comments

17 Feb 2010 - 10:56pm by Anonymous (not verified)

The second part is wrong, it is not work on windows platform if path contains spaces.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.