Buttons840
Buttons840

Reputation: 9637

Class.getResource() returns null in my Eclipse Application? Can't configure classpath?

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.

Upvotes: 6

Views: 21151

Answers (4)

keesp
keesp

Reputation: 311

I've had this problem occur, because the The Bundle-ClassPath setting in Manifest.MF MUST include . (see https://www.eclipse.org/forums/index.php/t/287184/), for instance:

Bundle-ClassPath: .,
 test.myapp.core

Bundle-ClassPath is not added automatically by the plugin wizards, so that can cause some problems.

Upvotes: 0

DwB
DwB

Reputation: 38300

Put the file in the top level directory in your source tree. This is often called "src". Then, when you build your project the file will be copied into your class directory (name varies). Finally, post build the file will be in your classpath (within the eclipse environment).

Class someClassObject = BlammyClassName.class;
someClassObject.getResource("my_resource_file.txt");

will return a URL to your resource.

someClassObject.getResourceAsStream("my_resource_file.txt");

will return a stream.

Edit: changed such that it does not reference Class methods statically.

Upvotes: 3

BalusC
BalusC

Reputation: 1108722

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.

Upvotes: 8

duffymo
duffymo

Reputation: 308763

Right click on the project and follow the properties.

Upvotes: 3

Related Questions