3

The original name of file is 1_00100 0042.jpg. I have a problem:

java.net.URISyntaxException: Illegal character in path at index 49: file:///opt/storage/user-data/attachments/1_00100\ 0042.jpg

Can you give me some solutions how to get this file using this bad path? I know that C# have Path class. Is there something similar in Java?

I tried to do next but not successfully:

private String replaceWhitespace(String str) {
    if (str.contains(" ")) {
        str = str.replace(" ", "%20");
    }
    return str;
}
jww
  • 97,681
  • 90
  • 411
  • 885
Yuliia Ashomok
  • 8,336
  • 2
  • 60
  • 69
  • Here you go: http://stackoverflow.com/questions/3487389/convert-string-to-uri – Dawnkeeper May 23 '14 at 11:35
  • 1
    @Dawnkeeper Standard Java (not Android JDK) doesn't have `Uri` but `URI` class which unfortunately doesn't have `parse` method. – Pshemo May 23 '14 at 12:16
  • Possible duplicate of [Accessing files with spaces in filename from Java](https://stackoverflow.com/q/5358850/608639), [Read file with whitespace in its path using Java](https://stackoverflow.com/q/9128288/608639), and friends. – jww Dec 17 '19 at 11:32

2 Answers2

4

Use File, it works with whitespaces:

String path = "file:///opt/storage/user-data/attachments/1_00100\\ 0042.jpg";
File f = new File(path);

If you want to replace spaces with %20 then use regex:

path.replaceAll("\\u0020", "%20");
Aboca
  • 575
  • 2
  • 9
  • This doesn't do what you think. For instance check result of `f.getName()` for user input `"file:///opt/storage/user-data/attachments/1_00100\\ 0042.jpg"`. – Pshemo May 23 '14 at 12:11
  • I don't understand the problem you are exposing, what's wrong with it? – Aboca May 23 '14 at 12:24
  • Your code will not compile because ``\`` in Java is special character which needs additional ``\`` to be literal, so you need to write it as `"\\"`. About result of `getName()` strange thing happens because in Java8 it will be only `0042.jpg` while in Java7 I see `1_00100\ 0042.jpg` (example http://ideone.com/m2FsuT). I am not sure why there is such difference. – Pshemo May 23 '14 at 12:32
  • oh you meant the escaping, that's right I missed it, sorry I'll edit it. – Aboca May 23 '14 at 18:32
2

I am not sure where did you get this path but I assume that \ before space was added to escape it so you need to change your method to also remove this \ before space.
Also since this method doesn't affect state of instance of your class you can make it static.

private static String replaceWhitespace(String str) {
    if (str.contains("\\ ")) {
        str = str.replace("\\ ", "%20");
    }
    return str;
}

Demo:

String file = "file:///opt/storage/user-data/attachments/1_00100\\ 0042.jpg";
file = replaceWhitespace(file);

URI u = new URI(file);
System.out.println(u.getRawPath());
System.out.println(u.getPath());

output:

/opt/storage/user-data/attachments/1_00100%200042.jpg
/opt/storage/user-data/attachments/1_00100 0042.jpg
Pshemo
  • 122,468
  • 25
  • 185
  • 269