Does class.getResource () return null in my Eclipse app? Can't configure classpath?

I am trying to use Class.getResource("rsc/my_resource_file.txt") to upload a file to an Eclipse application. However, no matter what I do in Eclipse, the classpath always contains only one entry in the Eclipse Launcher:

... / eclipse / plugins / org.eclipse.equinox.launcher_1.2.0.v20110502.pkc

How to set up classpath?

Note. At runtime, I define a class path with the following code:

 URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader(); for (URL classpathURL : cl.getURLs()) { System.out.println(classpathURL); } 

EDIT: More info.

The root of the problem is that Class.getResource("rsc/my_resource_file.txt") returns null. After doing a little experimentation in a simple 5-line "Java application", I thought I realized that the problem was with the class. Apparently, the classpath is a little different from the Eclipse app. I solved the problem by running Class.getResource("/rsc/my_resource_file.txt") Thanks BalusC.

+6
source share
3 answers

Please take a step back. Your specific problem is that the resource returns null , right? Are you sure his path is right? Like you, this applies to the package of the current class. Shouldn't the path start with / relative to the package root?

 URL resource = getClass().getResource("/rsc/my_resource_file.txt"); // ... 

Alternatively, you can also use the context class loader, it always refers to the root of classpath (package):

 ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL resource = loader.getResource("rsc/my_resource_file.txt"); // ... 

At least the Eclipse launcher is not to blame.

+8
source

Right-click on the project and follow its properties.

+3
source

Place the file in the top-level directory in the source tree. This is often called "src". Then, when you create the project, the file will be copied to your class directory (the name changes). Finally, the post-assembly of the file will be in your class path (in the eclipse environment).

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

will return the url of your resource.

 someClassObject.getResourceAsStream("my_resource_file.txt"); 

will return the stream.

Edit: changed so that it does not reference class methods statically.

+3
source

Source: https://habr.com/ru/post/898312/


All Articles