简体   繁体   中英

Can't Access File in Resources Folder

I'm trying to load an image that I have stored in my /src/main/resources folder. When I do, however, I keep running into a NullPointerException that stems from the resource not being found.

Here is the code snippet:

        try {
            String path = this.getClass().getClassLoader().getResource("bern.png").toString();
        } catch (IOException ex) {
            System.out.println(path);
        }

Here is an image of my project file tree:

我的项目文件树的图像

And here is an image of my target build file tree:

我的目标构建文件树的图像

Here is the NullPointerException stacktrace: https://pastebin.com/KqJVxWEL

I have tried using pretty well every possible path for the image file that I can think of. (/src/main/resources/bern.png, src/main/resources/bern.png, /bern.png, etc.).

I have also tried using getClass().getClassLoader().getResource() instead of getClass().getResource() . From what I understand, the only difference between the Class and ClassLoader version of getResource() is that the Class version is not inherently absolute relative to the root, whereas the ClassLoader version is.

When I run getClass().getResource("").toPath() , I get the path that leads to the classes directory. This aligns with what I've read about the getResource() method working with the target build file tree. However, I don't see the resources folder showing up anywhere in the target build; I think that's the core of my problem. I'm just not sure how to fix it.

I know this question has been asked numerous times before, but the answers to the other version of this question haven't helped me out much.

I'm using NetBeans 11, and this project is running on the Maven build system. I haven't done much work with Maven in the past, so forgive me if this problem is extremely easy to fix.

Anyone know how I'm approaching this wrong?

EDIT: The problem is not anything with my project structure or code as shown by the code compiling correctly when run using mvn via the command line. As a result, it's an issue with NetBeans specifically and the way that it is viewing the resources folder.

Read the resource contents as a Stream (instead of the URL or file path)

public static void main(String[] args) throws IOException {
        InputStream in = Application.class.getClassLoader().getResourceAsStream("bern.png");
        BufferedImage testImage = ImageIO.read(in);
        ImageIcon icon = new ImageIcon(testImage);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM