saving base64 decoded string into a zip file

6.6k views Asked by At

I am trying to save a base64 decoded string into a zip file using the mentioned code:

Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/home/wemohamm/Desktop/test.zip")));
out.write(decodedString);
out.close();

Here decodedString contains base64 decoded string and I can output it. I am running the code in rhel6 with Java 1.6. When I try to open the zip, it says error occurred while opening file.

The same code if I use with Windows 7 Java 1.6 with path c:\\test\test.zip is working fine.

Is the zip not getting saved correctly in rhel6 or if there is any code modifications I need to do?

2

There are 2 answers

1
sstan On BEST ANSWER

Don't create a string from your byte array (String decodedString = new String(byteArray);), to then use an OutputStreamWriter to write the string, because then you are running the risk of introducing encoding issues that are platform dependent.

Just use FileOutputStream to write out the byte array (byte[] byteArray) directly to file.

Something like:

try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("/home/wemohamm/Desktop/test.zip"), 4096)) {
    out.write(byteArray);
}

Actually, the above requires java 1.7+, because of the new try-with-resources statement.

For Java 1.6, you can do this:

BufferedOutputStream out = null;
try {
    out = new BufferedOutputStream(new FileOutputStream("/home/wemohamm/Desktop/test.zip"), 4096);
    out.write(byteArray);
} finally {
    if (out != null) {
        out.close();
    }
}
0
chris On

That won't work. You are writing to a ordinary file without packing the content. Use the java zip library with ZipOutputStream, ZipEntry and so on.