Java: how to get file from escaped url?

I get the URL that the local file finds (the fact that I get the URL is not in my control). The URL is escaped correctly as defined in RFC2396. How can I convert this to a Java file object?

Oddly enough, the getFile () URL method returns a string, not a file.

I created a directory called "/ tmp / some dir" (with the distance between "some" and "dir"), which is correctly located at the following URL: "file: /// tmp / some% 20dir" (citations added for clarity).

How to convert this URL to a Java file?

To tell more about my problem, the following prints are 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 am not asking why the first example prints false, and why the second example prints true using my hacky replaceAll, I ask how to convert the escaped URL to a Java file object.

EDIT : thanks everyone, it was almost a hoax, but not really.

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" ) ); 
+42
java url file escaping
Jan 29 '10 at 23:39
source share
3 answers
 URLDecoder.decode(url);//deprecated URLDecoder.decode(url, "UTF-8"); //use this instead 

See the corresponding question. How do you not view URLs in Java?

+19
Jan 29
source share

The File constructor accepts a URI in combination with the URL#toURI() should work:

 URL url = getItSomehow(); File file = new File(url.toURI()); 
+63
Jan 29 '10 at 23:48
source share

AFAIK likes this Paths.get(url.toURI()).toFile() best since Java 7. See also Converting a Java file: // URL to a file (...), platform independent, including UNC ways .

+4
Apr 03 '15 at 16:41
source share



All Articles