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

23

我正在尝试反序列化我的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 file = new File(url.getPath());

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

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

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

输入图像描述


1
尝试使用 getResource("classpath:xmlToParse/companies.xml") - sidgate
您不需要在xmlToParse之前加另一个"/"吗? - LearningPhase
代码已更新,请查看。 - Tom Wally
有没有解决方案?我遇到了相同的问题。 - Mateusz Niedbal
3个回答

47

我曾经遇到过同样的问题,尝试将一些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对象并反向操作...


我尝试过这个,在本地运行正常,但是在部署到开发环境后无法解析。 https://dev59.com/xrXna4cB1Zd3GeqPO6sX - BabyishTank
即使在本地也无法工作。 - Mateusz Niedbal

13
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());

2
一旦您将此spring项目部署到jar中,它就会中断。请参见https://dev59.com/BmIj5IYBdhLWcg3wUjoX - BabyishTank

-2

您应该提供一个绝对路径(因此添加一个前导的 ´/´,其中 resource-folder 是根文件夹):

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

检查资源文件夹是否包含在部署程序集中。 - Raphael Roth
我认为,我必须绑定这个文件夹... 有什么简单的方法可以做到吗? - Tom Wally

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接