简体   繁体   中英

NullPointerException on getting Resource

The following code will produce a NullPointerException on uri = ...

I tried ClassLoader.getSystemResource , getClass().getResource or getClass().getClassLoader().getResource

Don't mater if I remove the / at the beginning or remove it at the end, it still produce a NullPointerException..

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    private Main() {
        URI uri = null;

        try {
            uri = ClassLoader.getSystemResource("/resources/images/flags/").toURI();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        if (uri != null) {
            System.out.println(uri.toString());

            File folder = new File(uri);

            for (File file : folder.listFiles()) {
                System.out.println(file.getName());
            }
        }
    }
}

Project structure:

结构

Please try without "resources", because this is just the name of the folder. The content of this folder will be copied to the compiled classes.

This is the answer for my comment. Since resource is already part of the classpath, you have to change:

"/resources/images/flags/" 

To

"/images/flags/"

Also, you can try relative path like "images/flags/"

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