3

I have a collection of resources on the classpath something along the lines:

com/example/foo r1.txt r2.txt r3.txt bar/ b1.txt b2.txt baz/ x.txt y.txt 

I know that this package is on the class-path sitting in WEB-INF lib, what I want to able to traverse the class-path starting at com.example.foo looking for all the .txt files. Call a function with siganutre similar to the following.

List files = findFiles("com/example/foo","*.txt");

I am using spring 3.1 so I am happy to use any methods that are part of spring.

UPDATE: Solution using Spring based @jschoen suggestion below:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources("classpath:com/example/foo/**/*.txt"); 

The spring matches using ant style patters thus the need for the double **

0

1 Answer 1

2

You can use the Reflections library if I am not mistaken.

public static void main(String[] args) { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("your.test.more")) .setScanners(new ResourcesScanner())); Set<String> textFiles = reflections.getResources(Pattern.compile(".*\\.txt")); for (String file : textFiles){ System.out.println(file); } } 

It doesn't matter what package you put, you just need one to start with, and it will find all the others.

EDIT: Also there seems to be PathMatchingResourcePatternResolver in Spring that you can use. It has a getResources(String locationPattern) that I would assume you could use the pass the pattern ".*\\.txt" and would work the same way. I don't have Spring setup where I am at or I would have tested it out myself.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.