1

我必须从服务器获取 zip 文件到 Android 手机,编码为 Base64。因为文件很大(〜20MB),我使用下面的代码通过bufferSize = 1024 * 1024获取字符串,对其进行编码并将其写入文件。我通过方法 android.util.Base64.encode() 得到 bad-base64 错误。为什么?

编码:

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();
        }
    }
}
4

2 回答 2

2

首先,为什么是Base64?通常要做的事情是只发送压缩文件,然后让客户端解压缩它——这将节省带宽,因为 Base64 被限制为每个字符 6 位。如果您可以更改服务器代码,最好按原样提供 zip 文件。

无论如何,即使您按块获取文件,您也无法单独解码这些块 - 您必须将所有 1024*1024 字节块放在一起,然后解码很多。此操作需要 20MB 缓冲区。Base64 在每个块的末尾添加了一些终止符。维基百科文章有一个很好的解释。

另一种选择是将块大小设为三的倍数;在这种情况下,我认为 Base64 结果可以分成块并且与输入相同。值得一试。

于 2012-09-11T21:02:16.100 回答
1

我建议在 Base64.decode() 上设置断点并检查缓冲区中的内容。您很可能会看到导致解码错误的意外情况(来自您的服务器应用程序的一些错误或类似的东西)。

于 2012-09-11T20:56:44.750 回答