首页 > 解决方案 > 为什么这会抛出 java.nio.file.InvalidPathException?

问题描述

程序抛出

 Exception in thread "main" java.nio.file.InvalidPathException: Illegal char 
  <:> at index 2: ‪E:\New folder
      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)
      at 
 javaapplication10.ACDirectoryListenerServiceImpl.main(ACDirectoryListenerServiceImpl.java:93)
Java Result: 1

当我尝试获取文件的路径时

Path path = Paths.get("‪E:\\New folder");

这是为什么?获取路径时是否允许驱动器号?

标签: javaswingdirectory

解决方案


“:”是“在索引 2”,即字符串的第三个字符。驱动器号应位于索引 0,“:”应位于索引 1。

您的字符串中有一个零宽度字符。您可以通过使用箭头键逐个字母移动光标来查找字符。该字符是光标似乎对按键没有反应的地方。

当我从 Windows 的“文件属性”对话框、安全页面、“对象名称”复制文件路径时,我看到这种情况发生了,当我用鼠标从头到尾选择路径时,有一个非打印的 unicode “left-驱动器号之前的“右嵌入”字符 (U+202A)。即使启用它也不可见(我尝试过 Notepad++ 和 Eclipse)。当我从头到尾选择路径时,不会发生这种情况。

感谢 Slaw在评论中指出了正确的方向。


推荐阅读