yooouuri
yooouuri

Reputation: 2658

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:

Structure

Upvotes: 1

Views: 1942

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 30995

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/"

Upvotes: 0

Tobias Otto
Tobias Otto

Reputation: 1676

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.

Upvotes: 4

Related Questions