Within my program i have a line of code:
Path toRead = new File(getClass().getResource("/data.txt").toString()).toPath();
Whenever I try to run this I get an error:
Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 4
As a normal File it seems to run fine but as a Path it messes up, is there a solution to this?
I need it as a Path in order to use Files.copy()
.
The folder that data.txt is in is added as a source folder.
You should never assume that a URL
returned from getResource()
is referring to a file. You should only ever use URL.openStream()
. That is actually what getResourceAsStream()
does.
try (InputStream is = getClass().getResourceAsStream("/data.txt")) {
Files.copy(is, targetPath);
}