One common way to load a resource file is using Class.getResource(String name)
method, which searches from the classpath
of the application.
A FileReader
can read from a file even outside of the project folder with double dot notations. For example, with eclipse you can read workspace/test.txt
with ../test.txt
. But when I was playing with the getResource()
method, it can only get a file with the double dot notation when the file is under the bin
folder. If you place the file outside of the bin
folder, double dot notation no longer works. I tried to follow the source code to ClassLoader.getResource()
, ClassLoader.parent.findResouce()
, and sun.misc.Launcher$AppClassLoader
but was not able to figure out further. this is on windows 10.
I should add an example here. I have a test.txt file and Java project1 in eclipse.
workspace/project1/src/package1/test.java
can read the test.txt file from the
workspace/test.txt
location with "../test.txt" with FileReader (the default location for eclipse seems to be workspace/project1/). But with getResouce() the double dot notation works as long as the file is put inside of workspace/project1/bin but not out of the bin folder.
I have some questions about the above:
1, why the double dot notation cannot bring you out of the bin
folder with getResouce()
but can do that with FileReader
?
2, Considering the behavior of getResouce()
, I am assuming eclipse added the bin
directory to the project classpath
successfully. In the .classpath
file for the project, there is another line:
<classpathentry kind="src" path="src"/>
Is the src
folder is not added to classpath
? Since getResouce()
does not seem to search there.