【问题标题】:Base64 encode file and OutOfMemory errorBase64 编码文件和 OutOfMemory 错误
【发布时间】:2013-11-18 14:35:16
【问题描述】:

我有 .zip 文件,在上传到服务器之前我必须对其进行 Base64 编码。给定文件最大为 20 mb,这会导致 OutOfMemory 异常。 我使用此代码:

public String encodeZipToBase64(File zip) {

    StringBuffer sb = new StringBuffer();

    byte fileContent[] = new byte[1024];
    try 
    {
        FileInputStream fin = new FileInputStream(zip);
        while(fin.read(fileContent) >= 0) {
             sb.append(Base64.encodeToString(fileContent, Base64.DEFAULT)); //exception here
        }
    } catch(OutOfMemoryError e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return sb.toString();

}

附加到 StringBuilder 时发生异常。我可以做些什么来解决它?

谢谢!

【问题讨论】:

    标签: android zip base64 out-of-memory


    【解决方案1】:

    您应该将 HTTP 请求 OutputStream 作为参数传递并直接在读取循环中写入,而不是将整个请求作为 StringBuilder 缓冲在内存中。

    【讨论】:

    • 是的,我想这是唯一的方法。我只有现有的 rest api,写在我之前,不太可能改变:(
    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 2019-01-18
    • 2015-01-13
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多