0

I'm using a simple way to get my resources for the project. I'm using Eclipse, and I have a 'res' folder to hold the needed files. This is how I load stuff, for example a 'puppy.png' just in my res folder (no subfolders):

String path = "/puppy.png";
try {
    BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path));
} catch(Exception ex) { ex.printStackTrace(); }

And sometimes I get an input==null error, and sometiomes not! Not like this time puppy.png loaded but next time it won't. For some classes it always loads correctly, and for the other classes I always get this error. Can anyone explain why can this happen, and how can I fix it, but still use the getResourceAsStream() method?

LPeter1997
  • 17
  • 1
  • 6

2 Answers2

1

Please have a look at How to retrieve image from project folder?.

I have mentioned no of ways to read image from different paths.

You can try any one

// Read from same package 
ImageIO.read(getClass().getResourceAsStream("c.png"));

// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));

// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));

In your case the image must be in the same package where is the class and don't prefix /.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • Yes also see the javadoc of the method: Before delegation, an absolute resource name is constructed from the given resource name using this algorithm: If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'. Otherwise, the absolute name is of the following form: modified_package_name/name Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e'). – keuleJ Apr 22 '14 at 19:41
0

Note that if the resource returns null (meaning it doesn't exist), you will get this error.

Check the input returned like so:

String path = "/puppy.png";
try {
    InputStream is = getClass().getResourceAsStream(path);
    if (is == null) {
        //resource doesn't exist
    } else {
        BufferedImage image = ImageIO.read(is);
    }
} catch(Exception ex) { ex.printStackTrace(); }

Note that you most likely should be using String path = "puppy.png", seeing as you will already be in the content of the project folder.

Rogue
  • 11,105
  • 5
  • 45
  • 71