1

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.

Crimson Bloom
  • 287
  • 2
  • 13
  • 1
    The call to `getResource` returns a URL path (`file:/a/b/c/data.txt`); it's not a `File` path. – Elliott Frisch Mar 15 '16 at 00:34
  • @ElliottFrisch Well I need that URL turned into a `java.nio.file.Path` in order to use `java.nio.file.Files.copy()`. – Crimson Bloom Mar 15 '16 at 00:39
  • You shouldn't do that. If the file is packaged in a `.jar` file, the URL refers to a jar file entry, so it simply cannot be accessed like a `File`. – Andreas Mar 15 '16 at 00:39
  • @CodedApple Use `Files.copy(InputStream, Path)`, using the result from `getResourceAsStream()`. Remember to close the stream when done, preferably by using try-with-resources. – Andreas Mar 15 '16 at 00:41
  • @Andreas I only want to copy a file from within the jar to the directory that the jar is being run in, that's all. – Crimson Bloom Mar 15 '16 at 00:41
  • @Andreas Thanks, that worked... – Crimson Bloom Mar 15 '16 at 00:43
  • Possible duplicate of http://stackoverflow.com/questions/9707892/issues-using-getresource-with-txt-file-java – Andreas Mar 15 '16 at 00:48

2 Answers2

1

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);
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

Try This:

String pathToFile = getClass().getResource("/data.txt").toString()).toPath(); 
String  pathToFile = pathToFile.replace("/C:", "C:/");
Path toRead = Paths.get(pathToFile)
Magnus L
  • 63
  • 10