To answer your last concern about the slash: when you use getClass()
the search will begin from the calling class. If you don't use the first class the file will be looked for in examples/examples/resource
(since the calling class is in examples
) which doesn't exist. What the forward slash does is bring the search to the class path root.
This works within Eclipse project but not when exported to runnable JAR,
Moreover many suggest that InputStream
should be favored over FileInputStream
If you a resource is needed for you application and is packaged in the jar, it should be read from an URL, either via getClass().getResource()
which returns an actual URL to a resource, or getClass().getResourceAsStream()
which return the resource as a stream in the form of InputStream
, obtained from the URL. You can also getClassLoader()
, but here are the main differences
getClass()
- As stated above, the search will begin from the location of the calling class. So whatever package the class is in, that's where the search begins. A structure like this
ProjectRoot
src
com
example
MyClass.class
resources
resource.ttf
will cause the the search to begin from inside example
dir of the package. So if you try and use this path resources/resource.ttf
if will fail, because there is no resources
dir in the examples
dir. Using the /
will bring the search to the root of the class path, which is the src
(at least from IDE perspective - which will get jar'ed into a classes
). So /resources/resource.ttf
would work, as src/resources/resource.ttf
exists.
getClassLoader()
- begins it's search from the class path root, so the src
. You don't need the extra /
because resources/resource.ttf
is like saying it exists as src/resources/resource.ttf
.
On another note, when you use any form of a File
search, the search will be in terms of the local file system. So as to your question why using File
would work on your IDE, is because the IDE launches the program not from the jar, but from the IDE itself and uses the current working directory as the root path.
So the main thing to keep in mind is that when your file is an application resources, read it as such from the class path.
InputStream is = getClass().getResourcAsStream("/path/to/file");
Further explanation about the functionality of your IDE. Yours is eclipse. If you go to you project in yout file system, you will see a bin
file, in terms of your IDE is the class path. When you compile your code, the resources get copied into that path. That's where the IDE will search when you try and read as a file, as the project is the working directory, and using a non absolute path, that's where the searching happens