简体   繁体   中英

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.

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.

右键单击项目并按照属性进行操作。

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM