Java 中具有不同分隔符的统一路径

Uniform path with different separators in Java

我的输入路径没有统一的分隔符。

示例:

如何根据 Java 中路径的第一部分统一分隔符?

尝试 string.replace("\", "/");,然后 string.replace("//","/");。这会将每个“\”或“”替换为“/”。如果您想要不同的标准,请更改代码以将“/”替换为例如 OS 特定分隔符。

一般来说,您不应该使用字符串替换来处理 OS 路径。 Java 对 NIO 中的 OS 路径名有很好的支持 Path class.

只需将输入作为 Path p = Path.of(input) 传递即可生成路径实例,而不管输入斜杠的混合情况。然后 p.toString() 应该产生等效的 OS 路径:

String [] lines = {
   "path/to/file\example.txt",
   "\\path\to\file/example.txt",
};
for (String input : lines) {
    Path p = Path.of(input);
    System.out.println(input+" => "+p.toString());
    System.out.println("    getNameCount()="+p.getNameCount());
    do {
        System.out.println("    getParent()="+p.getParent() +"   getName()="+p.getFileName());
    } 
    while( (p = p.getParent()) != null);
}

请注意,Windows 将两种类型的斜杠作为 Windows 路径分隔符 \ 处理,以便 file\example.txt 被视为名为 example.txt 的文件的路径在文件夹 file 中,UNC 路径前缀作为一个父路径组件链接在一起 \SERVER\rootpath 而不是 \SERVER 然后 rootpath:

path/to/file\example.txt => path\to\file\example.txt
    getNameCount()=4
    getParent()=path\to\file   getName()=example.txt
    getParent()=path\to   getName()=file
    getParent()=path   getName()=to
    getParent()=null   getName()=path
\path\to\file/example.txt => \path\to\file\example.txt
    getNameCount()=2
    getParent()=\path\to\file   getName()=example.txt
    getParent()=\path\to\   getName()=file
    getParent()=null   getName()=null

Linux 将 Windows 路径分隔符 \ 作为文件名的一部分进行处理,以便 to/file\example.txt 被视为名为 file\example.txt 的文件的路径文件夹 to,UNC 路径名被视为包含多个 \:

的一个名称
path/to/file\example.txt => path/to/file\example.txt
    getNameCount()=3
    getParent()=path/to   getName()=file\example.txt
    getParent()=path   getName()=to
    getParent()=null   getName()=path
\path\to\file/example.txt => \path\to\file/example.txt
    getNameCount()=2
    getParent()=\path\to\file   getName()=example.txt
    getParent()=null   getName()=\path\to\file

我找到了解决方案。

这是我用来修复路径的方法:

private String uniformPath(String path) {
    String result = path;
    String[] splitted = path.split("[\/\\]");
    
    if(path.startsWith("\")) {
        result = String.join("\", splitted);
    }else if (path.startsWith("/")) {
        result = String.join("/", splitted);
    }else if (path.indexOf("/") > 0 || path.indexOf("\") > 0) {
        if(path.indexOf("/") < path.indexOf("\")) {
            if(path.indexOf("/") != -1) {
                result = String.join("/", splitted);
            }
        }else {
            if(path.indexOf("\") != -1) {
                result = String.join("\", splitted);
            }
        }   
    }

    return result;
}