Skip to content
Advertisement

Java getResource return null mac

I am very new to StackOverflow and I’ve done my best to fix this problem before posting this question here. I’m faced with the problem of getResource() returning null. I have a hunch that this is because I’m on a mac and the pathing is different here than on a PC (where this code seems to work fine). This is the code:

public class SampleClass
{
    static String imgpath = "/theimage.png";

    public static void main(String[] args)
    {
        System.out.println(imgpath);
        System.out.println(SampleClass.class.getResource(imgpath));
        try
        {
            BufferedImage image = ImageIO.read(SampleClass.class.getResource(imgpath));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

}

src, res and bin are all in the same directory and theimage.png is inside of res.

System.out.println(SampleClass.class.getResource("imgpath")); gives me null.

Advertisement

Answer

you get nullpointer exception because there is no image named imgpath in that folder

public class SampleClass
{
    static String imgpath = "/theimage.png";

    public static void main(String[] args)
    {
        System.out.println(imgpath);
        System.out.println(SampleClass.class.getResource(imgpath));
        try
        {
            BufferedImage image = ImageIO.read(SampleClass.class.getResource(imgpath));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

}

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement