如何从资源文件夹中获取文件。 Spring框架

如何从资源文件夹中获取文件。 Spring框架

问题描述:

我正在尝试解组我的xml文件:

I'm trying to unmarshal my xml file:

public Object convertFromXMLToObject(String xmlfile) throws IOException {
    FileInputStream is = null;
    File file = new File(String.valueOf(this.getClass().getResource("xmlToParse/companies.xml")));
    try {
        is = new FileInputStream(file);
        return getUnmarshaller().unmarshal(new StreamSource(is));
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

但我收到此错误:
java.io.FileNotFoundException:null(没有这样的文件或目录)

But I get this errors: java.io.FileNotFoundException: null (No such file or directory)

这是我的结构:

为什么我无法从资源文件夹中获取文件?谢谢。

Why I can't get files from resources folder? Thanks.

更新。

重构后,

URL url = this.getClass()。getResource(/ xmlToParse / companies.xml);
文件file = new File(url.getPath());

URL url = this.getClass().getResource("/xmlToParse/companies.xml"); File file = new File(url.getPath());

我可以更清楚地看到错误:

I can see an error more clearly:

java.io.FileNotFoundException:/content/ROOT.war/WEB-INF/classes/xmlToParse/companies.xml(没有这样的文件或目录)

java.io.FileNotFoundException: /content/ROOT.war/WEB-INF/classes/xmlToParse/companies.xml (No such file or directory)

它试图找到WEB-INF / classes /
我在那里添加了文件夹,但仍然出现此错误:(

It tries to find WEB-INF/classes/ I have added folder there, but still get this error :(

尝试将一些XML文件加载到我的测试类中时遇到同样的问题。如果使用Spring,从你的问题可以建议,最简单的方法是使用 org.springframework.core.io.Resource - Raphael Rot h已经提到了。

I had the same problem trying to load some XML files into my test classes. If you use Spring, as one can suggest from your question, the easiest way is to use org.springframework.core.io.Resource - the one Raphael Roth already mentioned.

代码非常简单。只需声明一个类型的字段org.springframework.core.io.Resource 并使用 org.springframework.beans.factory.annotation.Value - 就像那样:

The code is really straight forward. Just declare a field of the type org.springframework.core.io.Resource and annotate it with org.springframework.beans.factory.annotation.Value - like that:

@Value(value = "classpath:xmlToParse/companies.xml")
private Resource companiesXml;

要获得所需的InputStream,只需致电

To obtain the needed InputStream, just call

companiesXml.getInputStream()

你应该没问题:)

但请原谅我,我要问一件事:你为什么要在Spring的帮助下实现XML解析器?有很多内容:)例如。对于Web服务,有很好的解决方案可以将您的XML编组到Java Objects中并返回...

But forgive me, I have to ask one thing: Why do you want to implement a XML parser with the help of Spring? There are plenty build in :) E.g. for web services there are very good solutions that marshall your XMLs into Java Objects and back...