java.nio.file.InvalidPathException 当路径包含冒号 (:).



我需要构造一个包含冒号(:)的路径。实际上,路径不是Windows/linux中的文件夹/目录。这只是JCR回购的路径。下面的代码在路径包含冒号时给出 InvalidPathException

import java.nio.file.Path;
import java.nio.file.Paths;
public class TestCLass {
    public static void main(String[] args) {
        final Path path = Paths.get("com", "repo:access","resource");
        //final Path path = Paths.get("com", "repoaccess","resource"); //Output - com/repoaccess/resource
        System.out.println(path);
    }
}

例外

Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 8: comrepo:accessresource
    at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
    at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
    at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
    at java.nio.file.Paths.get(Paths.java:84)

是否有任何 API 可以访问冒号(:)还有其他特殊角色吗?

据我所知,Windows和Linux都不允许将":"放入文件名中。这就是为什么Java为这样的路径/文件名抛出InvalidPathException。没有 API 可以解决文件系统施加的限制。

最新更新