2013-02-12 105 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