线程"main" java.nio.file.InvalidPathException:UNC 路径缺少主机名:/\/



我正在尝试找出一种解决问题的方法。我正在使用java.nio。当我在Linux环境中执行Paths.get("/","/").toString()时,它可以正常工作,因为它是基于Linux的路径。但是,当我在Windows环境中执行它时,它会给我以下错误。

Exception in thread "main" java.nio.file.InvalidPathException: UNC path is missing hostname: //
        at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:113)
        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)

我知道这不是Windows中的有效路径系统。有什么办法可以在Windows和Linux上工作?

注意:我们的应用程序中有很多硬编码的前斜线。

Paths.get("/","/")在毫无用处,所以我不知道您的真实用例是什么。但是,您不应该在代码中使用硬编码的文件分离器。

假设您想获得文件系统的根目录,则可以做2件事:

  1. Paths.get(".").getRoot()如果$PWD=/home/blah
  2. 将返回/
  3. FileSystems.getDefault().getRootDirectories()

如果您不需要根目录,则Paths.get将使用File.separator构建Path

只有第一个参数应该是绝对的,即从路径分离器开始(/(。

如果第二个值可以是绝对的,即您要忽略前面的路径,请使用:

Paths.get("/").resolve("/").toString()   // returns "" on Windows

相关内容

最新更新