2016-04-04 237 views
14

我试图解组我的XML文件:如何从资源文件夹中获取文件。 Spring框架

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

这里是我的结构:

enter image description here

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

更新。

重构后,

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 /班/ 我已经添加的文件夹存在,但仍获得此错误:(

enter image description here

+1

尝试'的getResource(“类路径:xmlToParse/companies.xml”)' – sidgate

+0

惯于你一个“/”前需要xmlToParse – LearningPhase

+0

代码已更新。请检查出来。 –

回答

0

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

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

代码已更新。请检查出来。 –

+0

检查资源文件夹是否包含在部署程序集 –

+0

我认为,我必须绑定此文件夹...有没有简单的方法来做到这一点? –

34

我有同样的问题试图加载一些XML文件到我的测试类。如果你使用Spring,正如你可以从你的问题中得出的那样,最简单的方法是使用org.springframework.core.io.Resource-已经提到的Raphael Rot h。

代码非常简单。只需要声明的类型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对象和背部...

+0

不适用于非春季班。 –

10
ClassLoader classLoader = getClass().getClassLoader(); 
File file = new File(classLoader.getResource("fileName").getFile()); 
相关问题