簡體   English   中英

線程“ main”中的異常java.nio.file.InvalidPathException:UNC路徑缺少主機名:/ \\ /

[英]Exception in thread “main” java.nio.file.InvalidPathException: UNC path is missing hostname: /\/

我正在嘗試找出解決問題的方法。 我正在使用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("/","/")沒有用,所以我不知道您真正的用例是什么。 但是,您永遠不需要在代碼中使用硬編碼的文件分隔符。

假設您要獲取文件系統的根目錄,則可以做兩件事:

  1. 如果$PWD=/home/blahPaths.get(".").getRoot()將返回/
  2. FileSystems.getDefault().getRootDirectories()

如果不需要根目錄,則Paths.get將使用File.separator構造一個Path

只有第一個參數應該是絕對的,即以路徑分隔符( /\\ )開頭。

如果第二個值可以是絕對值,即要忽略前面的路徑,請使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM