java - 为什么我得到这个 InvalidPathException

标签 java

这段代码有问题。即我收到消息:

Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 2: [E:\Temp\564\324\123.txt]

public static void main(String[] args) throws Exception{
    Path sourseFile = Paths.get("E:\\Temp");
    Path[] result = searchFile(sourseFile, "123");
    for (Path path : result) {
        System.out.println(path);
    }        
}

public static Path[] searchFile (Path path, String fileName)throws Exception{

    DirectoryStream<Path> dirStream = Files.newDirectoryStream(path);
    ArrayList<Path> temp = new ArrayList<>();
    for (Path s : dirStream) {
        if (s.toFile().isDirectory()){
            temp.add(Paths.get(Arrays.toString(searchFile(s, fileName))));
        }
        else {
            if (s.toAbsolutePath().toString().contains(fileName)){
                temp.add(s.toAbsolutePath());
            }
        }
    }
    return temp.toArray(Path[]::new);
}

完整追踪

Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 2: [E:\Temp\564\324\123.txt] at java.base/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182) at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153) at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77) at java.base/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92) at java.base/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:229) at java.base/java.nio.file.Path.of(Path.java:147) at java.base/java.nio.file.Paths.get(Paths.java:69) at s09.Task1.searchFile(Task1.java:28) at s09.Task1.searchFile(Task1.java:28) at s09.Task1.main(Task1.java:13)

最佳答案

您似乎将字符串“[E:...]”(包括由 Arrays.toString 添加的周围方括号)传递给 Paths.get。这随后被解释为普通文件名,其中“:”字符确实是非法的。

关于java - 为什么我得到这个 InvalidPathException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56736003/

相关文章:

java - 创建可以像这样调用的 java 方法 : foo. bar().baz().quux()

java - 无法在 32 位操作系统上运行在 NetBeans(64 位 Windows 10 上)中创建的 .exe

java - Session.get 在 hibernate 中工作,同时逐步调试,但在 eclipse 中运行时不工作

java - 我应该选择哪种方法 fromValue() 函数枚举

java - 使用 Spring Boot Rest api 的 mysql 身份验证问题

java - 无法加载 javaagent

Java 反射 : get class of field

java - 为什么这个程序输出1?

java - Android 中的 recyclerview 中滚动时行项目宽度发生变化

java - Spring - 如何在创建和编辑用户时正确分配用户配置文件?