7

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
sakis kaliakoudas
  • 2,039
  • 4
  • 31
  • 51
  • But where do you tell the method that the image is in the resources folder? (not my down-vote). Note that resources are found relative to the class loader's path. – Hovercraft Full Of Eels Sep 15 '12 at 18:40
  • 3
    The `resources` folder needs to end up on the classpath; do you have it listed as a source folder? Is it being included at the root level in the jar? Etc--without knowing more it's difficult to be more helpful. – Dave Newton Sep 15 '12 at 18:44
  • not entirely familiar with what you are saying. How do I list something as a source folder? The thing is that even when my image is not in the folder, but just in the root of my project it still won't find it with getClass().getResource("/test.png"); – sakis kaliakoudas Sep 15 '12 at 18:53
  • 1
    The root of your project is probably not on the classpath, so the .png is invisible as far as the classloader is concerned. – DNA Sep 15 '12 at 19:08

3 Answers3

3

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

Community
  • 1
  • 1
DNA
  • 42,007
  • 12
  • 107
  • 146
  • That is indeed the reason why. I was under the impression that this is automatically done and I never had this happen in the past. Now I only have to figure out how to add my root in my classpath for a NetBeans project :D – sakis kaliakoudas Sep 15 '12 at 19:19
1

This works fine:

BufferedImage image = ImageIO.read(getClass().getClassLoader().getResourceAsStream("file_name"));
S. Esteves
  • 415
  • 4
  • 14
0

look out with ImageIO.read(getClass().getClassLoader().getResourceAsStream("file_name"));

...on windows you will get a URL encoded string, with %20 for spaces, so if you want to use that path to load a file, first call pathString.replace("%20", " ") ...that $hice just nailed me in live!

tom
  • 2,190
  • 1
  • 23
  • 27