加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何从资源文件夹获取文件. Spring框架

发布时间:2020-12-14 05:04:19 所属栏目:Java 来源:网络整理
导读:我试图解散我的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 File
我试图解散我的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 /
我已经添加了文件夹,但仍然得到这个错误:(

解决方法

我有同样的问题,试图加载一些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对象并返回…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读