Search code examples
javaeclipsemavengetresource

Double dot notation no longer works out of classpth (out of bin when using eclipse) for Class.getResouce()?


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.


Solution

  • why the double dot notation cannot bring you out of the bin folder with getResouce() but can do that with FileReader?

    Because they are looking for files in different namespaces. In the FileReader case, the namespace is the file system namespace with the root being your system's root directory. In the getResource() case, the namespace is the namespace that corresponds to the classpath. The top of that namespace typically corresponds to any directories on the classpath, and the root indexes of any archives on the classpath.

    In either case, you can't use ".." to navigate above the top of the namespace.

    Does eclipse add the 'src' directory to the classpath too when the app is run locally with eclipse?

    By default, I think the answer is No. Obviously, you can change that via the launcher configuration properties.

    If you want to be sure what the runtime classpath really is, print out the value of:

        System.getProperty("java.class.path")