Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate URL for File

Tags:

java

The default output of File.toURL() is

file:/c:/foo/bar

These don't appear to work on windows, and need to be changed to

file:///c:/foo/bar

Does the format

file:/foo/bar

work correctly on Unix (I don't have a Unix machine to test on)? Is there a library that can take care of generating a URL from a File that is in the correct format for the current environment?

I've considered using a regex to fix the problem, something like:

fileUrl.replaceFirst("^file:/", "file:///")

However, this isn't quite right, because it will convert a correct URL like:

file:///c:/foo/bar

to:

file://///c:/foo/bar

Update

I'm using Java 1.4 and in this version File.toURL() is not deprecated and both File.toURL().toString() and File.toURI().toString() generate the same (incorrect) URL on windows

like image 520
Dónal Avatar asked May 07 '10 14:05

Dónal


2 Answers

The File(String) expects a pathname, not an URL. If you want to construct a File based on a String which actually represents an URL, then you'll need to convert this String back to URL first and make use of File(URI) to construct the File based on URL#toURI().

String urlAsString = "file:/c:/foo/bar";
URL url = new URL(urlAsString);
File file = new File(url.toURI());

Update: since you're on Java 1.4 and URL#toURI() is actually a Java 1.5 method (sorry, overlooked that bit), better use URL#getPath() instead which returns the pathname, so that you can use File(String).

String urlAsString = "file:/c:/foo/bar";
URL url = new URL(urlAsString);
File file = new File(url.getPath());
like image 200
BalusC Avatar answered Oct 14 '22 09:10

BalusC


The File.toURL() method is deprecated - it is recommended that you use the toURI() method instead. If you use that instead, does your problem go away?


Edit:

I understand: you are using Java 4. However, your question did not explain what you were trying to do. If, as you state in the comments, you are attempting to simply read a file, use a FileReader to do so (or a FileInputStream if the file is a binary format).

like image 31
aperkins Avatar answered Oct 14 '22 09:10

aperkins