我有一个Microsoft Word文件的压缩base64字符串。如何将这个压缩的base64字符串转换为java中的原始文件。
我已尝试过此代码,但无法成功。这是我正在尝试的代码
public static void main(String[] args) throws IOException, DataFormatException {
File file = new File(outputFileName);
byte[] zipData = Base64.decodeBase64(compressed_base64_string);
GZIPInputStream zi = new GZIPInputStream(new ByteArrayInputStream(zipData));
String result = IOUtils.toString(zi);
zi.close();
InputStream filedata = new ByteArrayInputStream(result.getBytes("UTF-8"));
byte[] buff = new byte[1024];
FileOutputStream fos = new FileOutputStream(file);
while (filedata.read(buff) > 0) {
fos.write(buff);
}
fos.close();
}
此代码生成一个zip文件,其中有一些xml文件。但 compressed_base64_string 是从Microsoft Word文档生成的。我无法从此代码中获取原始文档。 请告诉我接下来要做什么才能获得原始文件
答案 0 :(得分:1)
以下代码对我有用
public static void main(String[] args) throws IOException, DataFormatException {
String outputFilePath = "document.docx";
File file = new File(outputFilePath);
FileOutputStream fos = new FileOutputStream(file);
byte[] zipData = Base64.decodeBase64(compressed_base64_string);
GZIPInputStream zi = new GZIPInputStream(new ByteArrayInputStream(zipData));
IOUtils.copy(zi, fos);
fos.close();
zi.close();
}
答案 1 :(得分:0)
public static boolean decode(String filename) {
try {
byte[] decodedBytes = Base64.decode(loadFileAsBytesArray(filename), Base64.DEFAULT);
writeByteArraysToFile(filename, decodedBytes);
return true;
} catch (Exception ex) {
return false;
}
}
public static boolean encode(String filename) {
try {
byte[] encodedBytes = Base64.encode(loadFileAsBytesArray(filename), Base64.DEFAULT);
writeByteArraysToFile(filename, encodedBytes);
return true;
} catch (Exception ex) {
return false;
}
}
public static void writeByteArraysToFile(String fileName, byte[] content) throws IOException {
File file = new File(fileName);
BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file));
writer.write(content);
writer.flush();
writer.close();
}
public static byte[] loadFileAsBytesArray(String fileName) throws Exception {
File file = new File(fileName);
int length = (int) file.length();
BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[length];
reader.read(bytes, 0, length);
reader.close();
return bytes;
}
编码( “路径/到/文件”);
解码( “路径/到/文件”);