Issue
I'm using this code to get a Path
for test-resource file in tests code:
Path target = Path.of(
Thread.currentThread().getContextClassLoader()
.getResource("target1").getFile()
);
The file is located at src/test/resources/target1
and copied on build to target/test-classes/tartget1
.
It's working fine on Unix-like systems, but on Windows it throws an exception:
java.nio.file.InvalidPathException: Illegal char <:> at index 2: /D:/a/project-name/repo-name/target/test-classes/target1
With the stacktrace (from CI machine):
at java.base/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
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:229)
at java.base/java.nio.file.Path.of(Path.java:147)
What is the correct way of getting a Path
in platform-agnostic way? I want to use same code for Unixes and Windows machines. (It's hard to debug this issue for me, because I don't have Windows machine only CI with Windows.)
Solution
The following works on my Windows machine whilst your example also fails as expected:
try {
Path target = Paths.get(Thread.currentThread().getContextClassLoader()
.getResource(FILE).toURI());
System.out.println(target);
} catch (URISyntaxException e) {
e.printStackTrace();
}
I assume this is because parsing a URI has a different implementation than parsing a string.
Answered By - Smutje