1

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.

Community
  • 1
  • 1
user1156544
  • 1,725
  • 2
  • 25
  • 51
  • You could always split off the `http://` with a `regex` and then use the `URLEncoder`, then re-add. Not efficient, but it might work. – BlackHatSamurai Jun 04 '13 at 23:07
  • Check out this answer, seems to be the same problem. http://stackoverflow.com/a/6199056/702568 – Kyle Kroboth Jun 05 '13 at 00:58
  • Thanks. It seems there is no real solution. I can check if the address has a "http://" but I have to do the same with "ftp://" and many others. This should have been addressed more formally already! It is strange it is not possible to create a URI if there are spaces or invalid characters (and there is no a pre-established solution - since URLEncoder does not work because it seems to be for another purpose as Kyle pointed out). – user1156544 Jun 05 '13 at 16:03

0 Answers0