有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java读取名称中带有空格的路径文件?

文件的原始名称为1_00100 0042.jpg。我有一个问题:

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

你能给我一些解决方案吗?如何使用这个坏路径获取这个文件?我知道C#有路径类。Java中有类似的东西吗

我尝试执行下一步,但未成功:

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

共 (2) 个答案

  1. # 1 楼答案

    我不确定您从何处获得此路径,但我假设添加了空间之前的\来转义它,因此您需要更改方法以同时删除空间之前的\
    此外,由于此方法不影响类实例的状态,所以可以将其设置为static

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

    演示:

    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());
    

    输出:

    /opt/storage/user-data/attachments/1_00100%200042.jpg
    /opt/storage/user-data/attachments/1_00100 0042.jpg
    
  2. # 2 楼答案

    使用文件时,它与空格一起工作:

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

    如果要用%20替换空格,请使用正则表达式:

    path.replaceAll("\\u0020", "%20");