Subhabrata Mondal
Subhabrata Mondal

Reputation: 536

Exception in thread "main" java.nio.file.InvalidPathException: UNC path is missing hostname: /\/

I am trying to figure out a way to solve my problem. I am using java.nio. When i execute Paths.get("/","/").toString() in Linux environment, it is working fine as it is Linux based path. But when i execute it in Windows environment, it gives me the following error.

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)

I understand this is not a valid path system in Windows. Is there any way so that i can work for both Windows and Linux?

Note: There are lot of hard coded Forward Slash in our application.

Upvotes: 0

Views: 1163

Answers (2)

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24563

Paths.get("/","/") is trivially useless, so I've no idea what your real use case is. However, you should never need to use hard-coded file separator in your code.

Assuming you want to get the root directory of a file system, you could do 2 things:

  1. Paths.get(".").getRoot() would return / if $PWD=/home/blah
  2. FileSystems.getDefault().getRootDirectories()

If you don't need the root directory, Paths.get would construct a Path using File.separator.

Upvotes: 1

Andreas
Andreas

Reputation: 159124

Only the first parameter should be absolute, i.e. start with a path separator (/ or \).

If the second value can be absolute, i.e. you want to ignore the preceding path, use:

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

Upvotes: 0

Related Questions