2013-02-12 109 views
0

我有一個XML文件,其中有一個名爲「CONTENIDO」的節點,在此節點中,我有一個以base64字符串編碼的PDF文件。錯誤解碼base64字符串

我想讀取這個節點,在base64中解碼字符串並將PDF文件下載到我的電腦。

問題是該文件與原始PDF格式具有相同的大小(以kb爲單位),並且具有相同的頁面數量,但是...所有頁面都是空白的,沒有任何內容,當我打開下載的文件會出現一個彈出窗口,並顯示「未知的特殊806.6n」錯誤。我不知道這意味着什麼。

我試着在互聯網上找到解決方案,用不同的方式來解碼字符串,但總是得到相同的結果...... XML是好的我已經檢查了base64字符串,並確定。 我也調試了代碼,我已經看到var「fichero」的內容我正在閱讀base64字符串也是好的,所以我不知道可能是什麼問題。

這是我的代碼:

package prueba.sap.com; 

import java.io.ByteArrayOutputStream; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.io.OutputStream; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerFactory; 

import org.w3c.dom.Document; 
import org.w3c.dom.NodeList; 

import sun.misc.BASE64Decoder; 

import javax.xml.bind.DatatypeConverter; 

public class anexoPO { 


    public static void main(String[] args) throws Exception { 
     FileInputStream inFile = 
       new FileInputStream("C:/prueba/prueba_attach_b64.xml"); 
     FileOutputStream outFile = 
       new FileOutputStream("C:/prueba/salida.pdf");  
     anexoPO myMapping = new anexoPO(); 
     myMapping.execute(inFile, outFile); 
     System.out.println("Success"); 
     System.out.println(inFile);   

    } 

    public void execute(InputStream in, OutputStream out) 
    throws com.sap.aii.mapping.api.StreamTransformationException { 

     try {  

      //************************Code To Generate The XML Parsing Objects*****************************//  
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      Document doc = db.parse(in); 
      Document docout = db.newDocument(); 

      NodeList CONTENIDO = doc.getElementsByTagName("CONTENIDO"); 
      String fichero = CONTENIDO.item(0).getChildNodes().item(0).getNodeValue(); 

      //************** decode *************/ 

       //import sun.misc.BASE64Decoder; 
       //BASE64Decoder decoder = new BASE64Decoder(); 
       //byte[] decoded = decoder.decodeBuffer(fichero); 

       //import org.apache.commons.codec.binary.*; 
       //byte[] decoded = Base64.decode(fichero); 

       //import javax.xml.bind.DatatypeConverter; 
       byte[] decoded = DatatypeConverter.parseBase64Binary(fichero); 

      //************** decode *************/ 

      String str = new String(decoded); 
      out.write(str.getBytes()); 

      } catch (Exception e) { 
       System.out.print("Problem parsing the file"); 
       e.printStackTrace(); 
       }  
    } 

} 

在此先感謝。

回答

2

肯定:

out.write(decoded); 
out.close(); 

字符串不能代表所有字節,PDF是二進制的。

也刪除sun.misc.BASE64Decoder的導入,因爲這個包並不是到處都存在。它可能會被編譯器刪除,但我不會打賭。

+0

謝謝!這解決了我的問題。 – Richal 2013-02-12 10:37:42