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" ) );