'Convert device path starting with \\?\ to Path
I want to read and write data to a HID device in a java program.
The device's path, in Windows, is formatted like so:
\\?\HID#VID_XXXX&PID_XXXX#...#{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. The \\?\ prefix is a special windows namespace.
I can use RandomAccessFile to open the device with no problem, because the constructor requires a String.
However, when i try to convert it to a Path, this happens:
Path.of("\\\\?\\HID#VID_XXXX&PID_XXXX#...#{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}");
Exception in thread "main" java.nio.file.InvalidPathException: Illegal character [?] in path at index 2: \\?\HID#VID_XXXX&PID_XXXX#...#{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
at java.base/sun.nio.fs.WindowsPathParser.nextSlash(WindowsPathParser.java:212)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:111)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at java.base/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92)
at java.base/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:232)
at java.base/java.nio.file.Path.of(Path.java:147)
at ...
Since i want to use the AsynchronousFileChannel class, i have to convert it to a Path first. Is there a way to do it?
Solution 1:[1]
Replacing \\?\ with \\.\ seems to do the trick:
String rawPath = "\\\\?\\HID#VID_XXXX&PID_XXXX#...#{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"
var newPath = Path.of(rawPath.replace("\\\\?\\", "\\\\.\\");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Psyvern |
