I am trying to get hold of a file ( or a directory ) under /WEB-INF/.../
outside of a request. I need it in a bean loaded at server startup.
A
This is how you can do it if you just want to access it from a Service (not through ServletContext):
final DefaultResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource("classpath:templates/mail/sample.png");
File myFile = resource.getFile();
Note that the last line may throw IOException
so you need to catch / rethrow
Note, that the file is here:
src\main\resources\templates\mail\sample.png
I use Spring DefaultResourceLoader and Resource to read inside WEB-INF or any resources in a *.jar file. Work like a charm. Good luck!
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
public static void myFunction() throws IOException {
final DefaultResourceLoader loader = new DefaultResourceLoader();
LOGGER.info(loader.getResource("classpath:META-INF/resources/img/copyright.png").exists());
Resource resource = loader.getResource("classpath:META-INF/resources/img/copyright.png");
BufferedImage watermarkImage = ImageIO.read(resource.getFile());
}
You can use classpath resource if the file is located in the WEB_INF\classes
directory. Which is where any files in your src/main/resources
directory will be copied to using a normal maven build ...
import org.springframework.core.io.Resource
...
final Resource yourfile = new ClassPathResource( "myfile.txt");
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("files/test.xml").getFile());
"files" folder should be child of "main/resources" folder
Not completely related to your question, but...
Here is some universal sulution i used to load properties from anywhere in web application like Spring does it (supporting WEB-INF/..., classpath:..., file:...). Is is based on using ServletContextResourcePatternResolver
. You will need ServletContext
.
private static Properties loadPropsTheSpringWay(ServletContext ctx, String propsPath) throws IOException {
PropertiesFactoryBean springProps = new PropertiesFactoryBean();
ResourcePatternResolver resolver = new ServletContextResourcePatternResolver(ctx);
springProps.setLocation(resolver.getResource(propsPath));
springProps.afterPropertiesSet();
return springProps.getObject();
}
I used the above method in my custom servlet context listener while conext was not yet loaded.
As long as your bean is declared in web application context you can obtain an instance of ServletContext
(using ServletContextAware
, or by autowiring).
Then you can access files in webapp directory either directly (getResourceAsStream()
, getRealPath()
), or using ServletContextResource
.
EDIT by momo:
@Autowired
ServletContext servletContext;
... myMethod() {
File rootDir = new File( servletContext.getRealPath("/WEB-INF/myDIR/") );
}