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" ) );
java url file escaping
SyntaxT3rr0r Jan 29 '10 at 23:39 2010-01-29 23:39
source share