Reputation: 536
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
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:
Paths.get(".").getRoot()
would return /
if $PWD=/home/blah
FileSystems.getDefault().getRootDirectories()
If you don't need the root directory, Paths.get
would construct a Path
using File.separator
.
Upvotes: 1
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