如何使用字符串路径名在WAR中打开资源文件? [英] How to open a resource file in a WAR using a string pathname?

查看:193
本文介绍了如何使用字符串路径名在WAR中打开资源文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 阅读器(阅读器) reader = new BufferedReader(new FileReader(path)); 

上面的路径是作为属性传递给此字符串的字符串通过Spring的 applicationContext.xml 文件创建类。



如果我想要将所有这些配置文件放在WAR中,这甚至可以完成?或者是组件不正确的,应该使用的getResourceAsStream()代替?



我浏览周围,发现了很多的info getResource() URI 。但是,我找不到是否可以在 applicationContext.xml 中创建正确的文件路径

DIV>

在弹簧环境最好是使用 spring resources API
简单示例:

  @Inject 
private ResourceLoader resourceLoader ;

public void someMethod(){
Resource resource = resourceLoader.getResource(file:my-file.xml);
InputStream is = null;
尝试{
is = resource.getInputStream();
//可以工作
....
}最后{
IOUtils.closeQuetly(is);




$ b如果你想访问外部文件(非类路径资源,它们应该位于归档中的META-INF /资源中),但是您应该将这些路径放在主属性文件中并将其加载到应用程序部署中。



编辑:在示例中将@Resource更改为@Inject

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

解决方案

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

这篇关于如何使用字符串路径名在WAR中打开资源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆