Question

I have the following code in a static class called Methods that is archived in a jar:

System.out.println(Methods.class.getResource("tagdict.txt")); // 1
URL test = Methods.class.getResource("tagdict.txt");          // 2
System.out.println(test.getPath());                           // 3
TagDictionary dict = new POSDictionary(test.getPath());       // 4

The first System.out (1) says:

rsrc:de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt

The second System.out (2) says:

de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt

Line 4 throws a

java.io.FileNotFoundException: de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt (No such file or directory)

The file tagdict.txt is placed in the same package as the Method.class, which is de/fhg/scai/bio/harsha/classificationworkflow.

I do not understand why line 4 throws a FileNotFoundException even though the file was found already inside the jar.

Was it helpful?

Solution

Line 3 just prints out the path component of the URL returned by getResource. It doesn't actually check if that path represents a real file on disk.

It looks like the POSDictionary constructor is trying to create a File using the path string passed to it, and this path doesn't actually represent an on-disk file, therefore throwing the exception.

I do not understand why line 4 throws a FileNotFoundException even though the file was found already inside the jar.

Because if the resource is in a JAR, then it's not a file. Such resources can only be accessed by opening input streams directly from the URL object, or by using getResourceAsStream() instead of getResource(). They can't be accessed using java.io.File, since they're not actual disk files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top