【问题标题】:How to get files from resources folder. Spring Framework如何从资源文件夹中获取文件。春天框架
【发布时间】:2016-07-24 06:50:40
【问题描述】:

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

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 (没有这样的文件或目录)

这是我的结构:

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

更新。

重构后,

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

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

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

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

【问题讨论】:

  • 试试getResource("classpath:xmlToParse/companies.xml")
  • 在 xmlToParse 之前是否需要另一个“/”
  • 代码已更新。请检查一下。

标签: java spring-mvc java-io fileinputstream


【解决方案1】:

我在尝试将一些 XML 文件加载到我的测试类时遇到了同样的问题。如果您使用 Spring,正如您的问题所建议的那样,最简单的方法是使用 org.springframework.core.io.Resource - 已经提到的 Raphael Roth。

代码非常简单。只需声明 org.springframework.core.io.Resource 类型的字段并使用 org.springframework.beans.factory.annotation.Value 对其进行注释 - 就像这样:

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

要获取所需的InputStream,只需调用

companiesXml.getInputStream()

你应该没事的:)

但是原谅我,我要问一件事:为什么要借助 Spring 来实现 XML 解析器?有很多内置:)对于 Web 服务,有非常好的解决方案可以将您的 XML 编组为 Java 对象并返回...

【讨论】:

【解决方案2】:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());

【讨论】:

    【解决方案3】:

    你应该给出一个绝对路径(所以添加一个加载'/',其中资源文件夹是根文件夹):

    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();
            }
        }
    }
    

    【讨论】:

    • 检查资源文件夹是否包含在部署程序集中
    • 我想,我必须绑定这个文件夹...有什么简单的方法可以做到吗?
    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 2015-01-12
    • 2019-03-24
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多