Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid getting URL encoded paths from URL.getFile()?

I'm having the following problem when trying to get the path of a given resource:

    System.out.println("nf="+new File(".").getAbsolutePath());      
    System.out.println("od="+new File(this.getClass().getResource(".").getFile());

The output I get is:

nf=C:\Users\current user\workspace\xyz\.
od=C:\Users\current%20user\workspace\xyz\bin\something

The problem lies with the %20 URL encoding thing. How to avoid it? Is there a direct way to avoid getting this kind of string in the first place, or should I just run the returned string against some method that will do the URL decoding?

Thanks

like image 783
devoured elysium Avatar asked Jan 19 '12 15:01

devoured elysium


People also ask

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

URL escape codes for characters that must be escaped lists the characters that must be escaped in URLs. If you must escape a character in a string literal, you must use the dollar sign ($) instead of percent (%); for example, use query=title%20EQ%20"$3CMy title$3E" instead of query=title%20EQ%20'%3CMy title%3E' .

How do you escape space in URL?

URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

Why does URL get encoded?

Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing into a URL.

What is getFile in Java?

URL getFile() method in Java with Examples The getFile() function is a part of URL class. The function getFile() returns the file name of a specified URL. The getFile() function returns the path and the query of the URL.


1 Answers

This is due to a URL handling quirk in the API. You can work around this by converting the URL string to a URI first:

new URI(this.getClass().getResource(".").toString()).getPath()

This will produce a String as follows:

"C:\Users\current user\workspace\xyz\bin\something"
like image 119
coudy Avatar answered Sep 20 '22 21:09

coudy