base 64解码并写入doc文件

时间:2014-12-24 11:54:10

标签: java base64 apache-poi filewriter

我有一个base64编码的字符串。看起来像这样

UEsDBBQABgAIAAAAIQDhD46/jQEAACkGAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .

我解码了String并使用FileWriter将其写入word文件。但是当我尝试打开doc文件时,我收到一条错误说明数据损坏的信息。

我想知道在解码数据后将内容写入word文档需要遵循的步骤。下面是我所做的错误代码。

     byte[] encodedBytes = stringBase64.getBytes();
     byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
     String decodeString = new String(decodedBytes);
     filewriter = new java.io.FileWriter("F:\xxx.docx”);
     BufferedWriter bw = new BufferedWriter(fw);
     bw.write(decodeString);

2 个答案:

答案 0 :(得分:4)

解码数据不是纯文本数据 - 它只是二进制数据。所以用FileStream而不是FileWriter

来写
// If your Base64 class doesn't have a decode method taking a string,
// find a better one!
byte[] decodedBytes = Base64.decodeBase64(stringBase64);
// Note the try-with-resources block here, to close the stream automatically
try (OutputStream stream = new FileOutputStream("F:\\xxx.doc")) {
    stream.write(decodedBytes);
}

甚至更好:

byte[] decodedBytes = Base64.decodeBase64(stringBase64);
Files.write(Paths.get("F:\\xxx.doc"), decodedBytes);

答案 1 :(得分:2)

请看一下。

    byte[]   encodedBytes = /* your encoded bytes*/

 // Decode data on other side, by processing encoded data
    byte[] decodedBytes= Base64.decodeBase64(encodedBytes );

    String yourValue=new String(decodedBytes);
    System.out.println("Decoded String is " + yourValue);

现在,您可以将此字符串写入文件并进一步阅读。