2012-06-23 45 views
0

我想從ZipInputStream中提取一個xml文件&其他內容並從xml創建我的對象解析zipinputstream。但是,我得到文件異常的過早結束 - 對於下面的代碼或流關閉 - 當我沒有while循環讀取inputStream。據我所知,ZipInputStream.getNextEntry獲取輸入流的下一個條目。文件過早結束。嘗試從Zipinputstream解析XML的異常

另外 - 當我通過創建一個實際的臨時文件運行它&通過輸入流(如在註釋的代碼) - 它處理得很好 - 但在我的情況下,我不會寫入磁盤 - 所以這一切必須在內存中發生。有人可以告訴我,我的代碼錯在哪裏,我能做些什麼來解決它?

ZipEntry entry; 
Map<String, byte[]> otherElements = new HashMap<String, byte[]>(); 
     entry =((ZipInputStream)inputStream).getNextEntry(); 
     while (entry != null) { 
      logger.debug("entry: " + entry.getName() + ", " + entry.getSize()); 
      System.out.println(entry.getName() + " - " + entry.getSize()); 

      if (entry.getName().equalsIgnoreCase("Document.xml")) { 
       /*File file = new File("C:\\tmp.xml"); 
       FileOutputStream fos = new FileOutputStream(); 
       int read = 0; 
       byte[] bytes = new byte[1024]; 

       while ((read = inputStream.read(bytes)) != -1) { 
        fos.write(bytes, 0, read); 
       } 
       InputStream fis = new FileInputStream();*/ 

       while(inputStream.available()>0){ 
        inputStream.read(); 
       } 

       myOutput = buildMyOutput((ZipInputStream)inputStream); 
       //fos.close(); 
       //fis.close(); 

// method that takes the input and creates the java object 
private MyObject buildMyOutput(InputStream xmlStream) throws Exception { 

    // build my objects 
    XStream xstream = ConvertUtil.getXStream(); 
    xstream.processAnnotations(MyObject.class); 
    MyObject myOutput = (MyObject) xstream.fromXML(xmlStream); 
    return myOutput; 
} 

回答

0

發現了什麼問題是: XStream的是失去的編碼信息&設置爲null [上Codehaus的JIRA鏈接] [1] https://開頭的JIRA .codehaus.org/browse/XSTR-441

因此,基於這個輸入,我將輸入流複製爲UTF-8,然後使用UTF-8編碼格式調用buildMyOutput方法。 刪除下面的代碼片段 -

while(inputStream.available()>0){ 
     inputStream.read(); 
} 

,並改變了buildMyOutput電話如下

String xml = IOUtils.toString(zipInputStream, "UTF-8"); 
    InputStream documentXmlIS = IOUtils.toInputStream(xml); 
    map = buildMyOutput(documentXmlIS); 
+0

後來我才意識到,真正的罪魁禍首是我的IDE設置默認情況下,而不是系統默認使用UTF-8 。因此,根據您使用的IDE,檢查IDE的編碼也是值得的(完全無法編程的修復程序性問題!) – conphident4

相關問題