Sheikh
Sheikh

Reputation: 539

Java Get All Files in a Package

I'm trying to get all the files in a package in Java using this code:

public static ArrayList<String> getThemes() {
        ArrayList<String> themes = new ArrayList<>();

    File folder = new File(Main.class.getResource("fxml/").toString());

        for (File file : folder.listFiles()) {
            if (file.getName().endsWith(".css"))
                themes.add(file.getName().replaceFirst("[.][^.]+$", ""));
        }

    return themes;
}

This code is supposed to give me an ArrayList of all the css files in the package called fxml (Full: dev.thetechnokid.rw.fxml).

I've used many other different ways, including using the current directory and the complete file path, but it still gives a NullPointerException. The stack trace doesn't give enough info, just the FXML LoadException.

What is wrong with this code?

Upvotes: 1

Views: 6962

Answers (3)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

I'm pretty sure Class.getResource() only detects files, not folders. <-- I stand corrected.

Class.getResource is not a very useful abstraction here. This mechanism is mainly useful when you don't know whether a resource will be in a file system or inside an archive. The ClassLoader abstracts that away.

In your case you know you have files, so you might as well use their API directly:

List<String> cssFileNames = Files.walk(Paths.get("fxml"))
                                 .map(Path::getFileName)
                                 .map(Path::toString)
                                 .filter(n -> n.endsWith(".css"))
                                 .collect(Collectors.toList());

But if you really must use the ClassLoader, one trick is to start with a known file, then move up one level and go from there:

Path path = new File(
        Main.class.getResource("fxml/iKnowThisFileExists.txt").toURI()
).getParentFile().toPath();
List<String> cssFileNames2 = Files.walk(path)
                                 .map(Path::getFileName)
                                 .map(Path::toString)
                                 .filter(n -> n.endsWith(".css"))
                                 .collect(Collectors.toList());

Upvotes: 4

Khalil M
Khalil M

Reputation: 1858

I would suggest:

URL packageURL;
packageURL = classLoader.getResource("fxml/"); 
URI uri = new URI(packageURL.toString());
File folder = new File(uri.getPath());

Upvotes: 0

Viet
Viet

Reputation: 3409

try use getFile instead of toString

File folder = new File(Main.class.getResource("fxml/").getFile());

Upvotes: 0

Related Questions