views:

256

answers:

3

I'm receiving an URL that locates a local file (the fact that I receive an URL is not in my control). The URL is escaped validly as defined in RFC2396. How can I transform this to a Java File object?

Funnily enough, the URL getFile() method returns a String, not a File.

I've created a directory called "/tmp/some dir" (with a spacing character between "some" and "dir"), which is correctly located by the following URL: "file:///tmp/some%20dir" (quotes added for clarity).

How can I convert that URL to a Java File?

To give more detail about my issue, the following prints false:

URL url = new URL( "file:///tmp/some%20dir" );
File f = new File( url.getFile() );
System.out.println( "Does dir exist? " + f.exists() );

While the following (manually replacing "%20" with a space) prints true:

URL url = new URL( "file:///tmp/some%20dir" );
File f = new File( url.getFile().replaceAll( "%20", " " ) );
System.out.println( "Does dir exist? " + f.exists() );

Note that I'm not asking why the first example prints false nor why the second example using my hacky replaceAll prints true, I'm asking how to convert an escaped URL into a Java File object.

EDIT: thanks all, this was nearly a dupe but not exactly.

Stupidly I was looking for a helper method inside the URL class itself.

The following works as expected to get a Java File from a Java URL:

URL url = new URL( "file:///home/nonet/some%20dir" );
File f = new File( URLDecoder.decode( url.getFile(), "UTF-8" ) );
+1  A: 

Try passing the URL through URLDecoder.decode().

More specifically, if you just pass your original URL though decode(), it'll no longer be a valid URL (due to the spaces). You only want to decode the file part of the URL:

URL url = new URL( "file:///tmp/some%20dir" );
File f = new File( URLDecoder.decode(url.getFile()) );
skaffman
+2  A: 
URLDecoder.decode(url);

See related question http://stackoverflow.com/questions/623861/how-do-you-unescape-urls-in-java

Cesar
+4  A: 

The File constructor taking an URI in combination with URL#toURI() should work:

URL url = getItSomehow();
File file = new File(url.toURI());
BalusC
+1, this is excellent.
Webinator
You're welcome. Why is this then not accepted by the way? :o
BalusC
Well ... you only answered the part about getting the file from the URL. But hey, its the OP's choice as to which answer he thinks is *most* helpful.
Stephen C