Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java getResource() not working

this is driving me crazy. I have a NetBeans project in a folder with the following structure:

MyProject
---- build
---- src
---- resources

in src my code is in packages. What I am trying to do is to use

getClass().getResource("/resources/new.png"); 

from a class in package com.my.package but it just refuses to work! The "new.png" image is in the resources folder. Am I missing something here?

After a lot of playing around and moving the "new.png" image here and there to see when it will find the image, it finally worked but only when I put the image in the build folder. So what do I have to do to make this work ?

edit: sorry, wrong String in method parameter. Corrected now

like image 696
sakis kaliakoudas Avatar asked Sep 15 '12 18:09

sakis kaliakoudas


People also ask

How to access a file in Resource folder in Java?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().

How to get xml file from resources in Java?

You need to make sure that Eclipse includes /resources folder into the application classpath. Open your launcher from Run Configurations , goto Classpath tab and if it's not there - add it. The file can be read with this. getClass().


1 Answers

I'm not familiar with NetBeans, but the problem is probably that the resources folder (or the root of the project, for that matter) is not on the classpath, unlike build.

You need to configure NetBeans to add the root folder, or resources to the classpath, and load the file relative to there.

See also this question: Java - getClassLoader().getResource() driving me bonkers

like image 159
DNA Avatar answered Oct 02 '22 23:10

DNA