Reputation: 57
I have a compressed base64 string of a Microsoft Word file. How to covert this compressed base64 string into its original file in java.
I have tried this code, but could not succeed. Here is the code I am trying
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();
}
This code is generating a zip file in which there are some xml files. But compressed_base64_string is generated from a microsoft word document. I am not able to get original document from this code. Please tell me what should I do next to get the original document
Upvotes: 0
Views: 3558
Reputation: 57
The following code worked for me
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();
}
Upvotes: 1
Reputation: 29
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;
}
encode("path/to/file");
decode("path/to/file");
Upvotes: 0