java – 如何从资源文件夹获取文件. Spring框架
我试图解散我的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(); } } } 但我得到这个错误: 这是我的结构: 为什么我无法从资源文件夹获取文件?谢谢. 更新. 重组后, URL url = this.getClass().getResource(“/ xmlToParse / companies.xml”); 我可以更清楚地看到错误: 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对象并返回… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |