且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用字符串路径名在WAR中打开资源文件?

更新时间:2023-11-06 23:33:16

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