How to open a resource file in a WAR using a string pathname?

≡放荡痞女 提交于 2019-12-24 00:52:14

问题


I am building a WAR/EAR and one of my components reads in many custom configuration files using File IO:

Reader reader = new BufferedReader(new FileReader(path));

The path above is a String that is passed as a property to this class through Spring's applicationContext.xml file.

What String path do I specify if I want to put all these configuration files inside a WAR? Can this even be done? Or is the component incorrect and should be using getResourceAsStream() instead?

I browsed around and found a lot of info on getResource() and URI. However, I could not find whether it is possible to create the right file path to a resource inside applicationContext.xml


回答1:


In spring environment it's better to use spring resources API Simple example:

@Inject
private ResourceLoader resourceLoader;

public void someMethod() {
    Resource resource = resourceLoader.getResource("file:my-file.xml");
    InputStream is = null;
    try {
        is = resource.getInputStream();
        // do work
        ....
    } finally {
        IOUtils.closeQuetly(is);
    }
}

If you want to access external files (non-classpath resources, which should be located in META-INF/resources within the archive) with non fixed paths you should put such paths in main properties file and load it on app deploy.

edit: change @Resource to @Inject in example




回答2:


The key to accessing files is to make them available in your classpath. By default in a WAR file all the files under WEB-INF/classes are added to the classpath and you can reference those files.

For example: lets assume this is your WAR file structure

webapp.war
 |
 |---> WEB-INF
 |------|
 |      |----> classes
 |              |----> MyResource.properties
 |---> index.html
 |---> images
 |-------|
 |       ----> logo.gif

You can access your "MyResource.properties" using the following API

Reader reader = new BufferedReader(new FileReader("MyResource.properties"));

Hope this helps.

Good luck!



来源:https://stackoverflow.com/questions/9775363/how-to-open-a-resource-file-in-a-war-using-a-string-pathname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!