问题
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;
}
回答1:
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");
回答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
来源:https://stackoverflow.com/questions/23828105/read-file-with-whitespace-in-name-using-java