2016-04-04 161 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()); 
相關問題