我有一个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);
答案 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);
现在,您可以将此字符串写入文件并进一步阅读。