Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to get a File from an escaped URL?

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" ) ); 
like image 419
SyntaxT3rr0r Avatar asked Jan 29 '10 23:01

SyntaxT3rr0r


People also ask

How do you escape special characters in a URL in Java?

Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server.

How do I convert a string to a URL in Java?

In your Java program, you can use a String containing this text to create a URL object: URL myURL = new URL("http://example.com/"); The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question.


2 Answers

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

URL url = getItSomehow(); File file = new File(url.toURI()); 
like image 89
BalusC Avatar answered Sep 19 '22 14:09

BalusC


URLDecoder.decode(url);//deprecated URLDecoder.decode(url, "UTF-8"); //use this instead 

See related question How do you unescape URLs in Java?

like image 22
Cesar Avatar answered Sep 18 '22 14:09

Cesar