I cannot believe that this has not been addressed in Java YET.
I have seen Android: howto parse URL String with spaces to URI object?, where the 1st answer represent exactly my problem.
I have a string containing a file location. This can be a file in the system (/... or c:....) or a URL (http://....., ftp://...., etc) If the file is specified in the system or in a URL is unknown beforehand.
To distinguish between both I use the
new URI(string)
and then ask:
uri.isAbsolute()
This works fine... But guess what - if the path has a space I get an exception! (java.net.URISyntaxException) So to solve this, what I do is a preliminary:
URLEncoder.encode(string, "UTF-8");
But now, guess what - in case I receive a "http://.." all special characters are replaced, and now the "isAbsolute()" does not recognize it as an absolute URI.
Of course I could do a:
string.replace(" ", "%20")
But then... what happens if the name had a strange character different from a space, such as a Chinese or a French character?? Do I have to replace them all myself? I guess Java SHOULD have something to deal with this situation in a higher level. This is a very common problem, but I was not able to find a proper answer.