• Post Reply Bookmark Topic Watch Topic
  • New Topic

instance.class.getResource() returns an url that is wrong.  RSS feed

 
Daniel Larsson
Greenhorn
Posts: 9
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm using the class.getResource(filename), where filename is the absolute path to a package.

It responds and gives me an url that is not null, but spaces and nonenglish symbols are replaced with lots of strange symbols when I print it out to System.out.println()
When I make a file with that url and check file.exists() it says false.

The path looks correct if I disregard the strange symbols.

Is there some way of doing this that is portable and ensures that I can retrieve a path that works, regardless of symbols on the path, and regardless if its in a jar or not? I never managed to get it working properly.

Or maybe the strange symbols aren't the problem, but what could it be then?

I'm running windows xp and using pathnames with nonenglish symbols in them.

please help.
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, yeah, when you use anything other than letters and numbers in a file name, its URL will be the URL-encoded version of the file name. Spaces are replaced by %20, other characters are replaced by % followed by the ASCII value of the character (if it's ASCII) or % followed by the UTF-8 encoding of the character's value (if it isn't ASCII).

You can't use that string directly to create a File object, because obviously you'd need to URL-decode it. There's a File(URI) constructor, though, so you could use that if you converted the URL to a URI. Which is also possible: check the API docs for URL.

That should be usable and portable, but Java has historically managed to screw up its dealing with non-ASCII file names. Although I haven't seen forum posts about that for quite some time, so perhaps they have cleaned up that mess.
 
Daniel Larsson
Greenhorn
Posts: 9
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. URI decoded the string correctly and now it works.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!