0

I am trying to load a bmp image into my java program, Ive tried many different solutions, none of them are working. Every attempt leads to a NullPointerException. My NetBeans Project directory is set up as:

Project/src/main/java/com/username/programName/ - Where I have my code Project/src/main/resources/ - Where I have img.bmp

This is in java 1.8.

    public static void main(String[] args) {
        FileHandler handler = new FileHandler();
        handler.test();
    }
}

    void test() {
        File file = new File(getClass().getClassLoader().getResource("src/main/resources/img.bmp").getFile());
    }
}

I would simply like to be able to load the image. Everything I've tried so far has resulted in NullPointer.

ikilltheundead
  • 149
  • 1
  • 4
  • 1
    There are so many problems in this code. 1. ClassLoader.getResource() loads resources from the runtime classpath. Your project directory is not in the runtime classpath, so the path src/main/resources/img.bmp is invalid. It should just be `img.bmp`. 2. A classpath resource is NOT a file. A file is located in the file system. A classpath resource, at runtime, is bundled into a jar file, and is thus not on the file system. So, DO NOT use any file IO to load the resource. Just use getResourceAsStream() to get an inputStream on that resource. Or use getResource() to get a URL. – JB Nizet May 05 '19 at 09:56
  • @JB_Nizet, assuming you permit me to be so bold, I would suggest you convert your comment to an answer. – Abra May 05 '19 at 10:00
  • Have you read [Location-Independent Access to Resources](https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html)? – Abra May 05 '19 at 10:04

0 Answers0