tags:

views:

38

answers:

2

Is there any easy way to convert a URL that contains to two-byte characters into an absolute path?

The reason I ask is I am trying to find resources like this:

URL url=getClass().getResources("/getresources/test.txt");
String path=url.toString();
File f=new File(path);

The program can't find the file. I know the path contain '%20' for all spaces which I could convert but my real problem is I'm using a japanese OS and when the program jar file is in a directory with japanese text (for example デスクトップ) I get a whole bunch of garbage like this:

%e3%83%87%e3%82%b9%e3%82%af%e3%83%88%e3%83%83%e3%83%97

I think I could get the UTF-8 byte codes and convert this into the proper characters to find the file, but I'm wondering if there is an easier way to do this. Any help would be greatly appreciated.

nt

+1  A: 

File has a constructor taking an argument of type java.net.URI for this case:

File f = new File(url.toURI());
Moritz
I tried this. When I run the program in Netbeans it works, but when a build it is doesn't work.
ntmp
The error I'm getting is:java.lang.IllegalArgumentException: URI is not hierarchical
ntmp
Could it be that you are bundling your app with the resources in a `.jar`-file? You cannot create a `File` object from that `URI` then as the resource is not a file but an entry in that `.jar`.
Moritz
Ah I see. So since I am bundling it in a .jar file, is there any solution here?
ntmp
No. You would have to read from the resource through an `InputStream` either by calling `url.openStream()` or directly via `getClass().getResourceAsStream("resource.txt")`. If you need to know where on disk your `.jar` is you can inspect the `URL` returned but you cannot create a `File` referencing your resource inside that `.jar`.
Moritz
+1  A: 
URL url=getClass().getResources("/getresources/test.txt");
File f=new File(url.toURI());
Noel Ang
thx, as i was saying below, this only works in netbeans. when i compile the app i run into an error.
ntmp
Moritz got it. A File object cannot instantiate using a URL to an archived resource. You'll have to stream it.
Noel Ang