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
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' .
URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With