I have to get zip file from server to Android phone, encoded to Base64. Because the file is large (~20MB) I am using below code for getting the String by bufferSize=1024*1024, encoding it and writing it to file.
I get bad-base64 error by the method android.util.Base64.encode(). Why?
The code:
int bufferSize = 1024 * 1024;
byte[] buffer = new byte[bufferSize];
FileOutputStream fileOutputStream = null;
InputStream inputStream = null;
try {
fileOutputStream = new FileOutputStream(this.path + "/" + this.zipFileName);
inputStream = connection.getInputStream();
int bytesRead;
//read bytes
while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) > 0) {
byte[] zipBytes = Base64.decode(buffer, 0, bytesRead, Base64.DEFAULT);
fileOutputStream.write(zipBytes);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
First of all, why Base64? The usual thing to do would be to just send the zipped file and then let the client decompress it — it is going to save bandwidth since Base64 is limited to 6 bits per character. If you can change the server code it would be best to serve the zip file as is.
Anyway, even if you get the file by chunks you cannot decode those chunks separately — you have to put all of the 1024*1024 bytes chunks together and then decode the lot. You need a 20MB buffer for this operation. Base64 adds some terminator characters to the end of each chunk. The wikipedia article has a quite good explanation.
Another option would be make the chunk size a multiple of three; in this case I think that the Base64 result could be divided in chunks and be identical to the input. It is worth a try.