zesaro
zesaro

Reputation: 31

Read all Files from a package in Java

I would love to know how I can read the whole entries from a package in Java. With getRessource() you can get a single file. But I want them all! My plan is to read all Files from a folder/package (without subdir) and then use a Stream to filter the entries.

Hope you can help me out.

Upvotes: 1

Views: 1446

Answers (3)

Ducaz035
Ducaz035

Reputation: 3132

You can do so with the Reflections library.

One may just create a reflections object and let it do the scanning for you. It would be as easy as doing something like

Reflections reflections = new Reflections("my.package");
Set<String> resourceStrings = reflections.getResources(s -> true /*match all resources*/);
Set<URL> resources = resourceStrings.stream()
                                    .map(s -> getClass().getResource(s))
                                    .collect(Collectors.toSet())

Upvotes: 1

randers
randers

Reputation: 5146

You can achieve this using the Spring Framework. Even if you are not developing a Spring application, you can still use their utility methods. You want to use PathMatchingResourcePatternResolver:

public Resource[] getResources(String package)
{
    PathMatchingResourcePatternResolver pmrpr = new PathMatchingResourcePatternResolver();
    // turns com.myapp.mypackage into /com/myapp/mypackage/*
    return pmrpr.getResources("/" + package.replace(".", "/") + "/*");
}

For reference, see:

If you are using Maven, use this dependency:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>

Upvotes: 1

dryairship
dryairship

Reputation: 6077

You can get a list of all the files and then filter them:

File d = new File(System.getProperty("user.dir")); // user.dir returns the current working directory.

for(File f : d.listFiles())
{
    //do what you want to do
}

Upvotes: -1

Related Questions