I want to read a bunch of text files, by loading them as resources using the context classloader.
URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("folder/foo.txt");
Is there some way to get a list of resources whose names match a given pattern? For eg:
URL[] matchingUrls = someLibrary.getMatchingResources("folder/*.txt");
Libraries like Spring can scan the classpath to find classes with a given annotation, so I am wondering if there something similar to load a bunch of resources.
Classpath in Java is not only used to load . class files, but also can be used to load resources e.g. properties files, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL.
We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt"); InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt"); InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");
By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath. and all will work fine and I'm happy since I can have my static content under the src directory.
Comment from "Binil Thomas" was on the right track, I was looking for confirmation that Spring's PathMatchingResourcePatternResolver could be used from Java Config so that I could give the resulting "Resource" list to the Spring Hibernate SessionFactory.mappingLocations without having to update the list of Hibernate *.hbm.xml files every time a new mapping file was added. I was able to achieve this with the PathMatchingResourcePatternResolver using the below code:
import org.hibernate.SessionFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
...
ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
Resource [] mappingLocations = patternResolver.getResources("classpath*:mappings/**/*.hbm.xml");
sessionFactory.setMappingLocations(mappingLocations);
Works like a charm.
Just use:
@Value("classpath:folder/*.xml")
Resource[] resources;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With