线程" main"中的例外情况java.nio.file.InvalidPathException:UNC路径缺少主机名:/ \ /

时间:2018-04-04 05:01:27

标签: java nio

我正试图找出解决问题的方法。我正在使用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上工作吗?

注意: 在我们的应用程序中有很多硬编码的Forward Slash。

2 个答案:

答案 0 :(得分:1)

Paths.get("/","/")非常无用,所以我不知道你的真实用例是什么。但是,从不需要在代码中使用硬编码文件分隔符。

假设您想要获取文件系统的根目录,您可以做两件事:

    如果Paths.get(".").getRoot()
  1. /将返回$PWD=/home/blah
  2. FileSystems.getDefault().getRootDirectories()
  3. 如果您不需要根目录,Paths.get将使用Path构建File.separator

答案 1 :(得分:0)

只有第一个参数应该是绝对的,即以路径分隔符(/\)开头。

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

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