Issue
I am trying to use Class.getResource("rsc/my_resource_file.txt")
to load a file in an Eclipse application. However, no matter what I do in Eclipse the classpath always contains just one entry to the Eclipse Launcher:
.../eclipse/plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.pkc
How can I configure the classpath?
Note: At runtime I am determining the classpath with the following code:
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
for (URL classpathURL : cl.getURLs()) {
System.out.println(classpathURL);
}
EDIT: Further information.
The root of the problem is that Class.getResource("rsc/my_resource_file.txt")
is returning null. Having done some small experiments in a simple 5 line "Java Application" I thought I had figured it out and that the problem was related to the classpath. Apparently the classpath behaves a little different with an "Eclipse Application". I solved the problem by doing Class.getResource("/rsc/my_resource_file.txt")
Thanks BalusC.
Solution
Please take a step back. Your concrete problem is that the resource returns null
, right? Are you sure that its path is right? As you have, it's relative to the package of the current class. Shouldn't the path start with /
to be relative to the package root?
URL resource = getClass().getResource("/rsc/my_resource_file.txt");
// ...
Alternatively, you can also use the context class loader, it's always relative to the classpath (package) root:
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL resource = loader.getResource("rsc/my_resource_file.txt");
// ...
At least, the Eclipse launcher is not to blame here.
Answered By - BalusC