简体   繁体   English

ByteArrayOutputStream过度使用RAM内存

[英]Extream usage of RAM memory by ByteArrayOutputStream

So my problem sounds like this. 所以我的问题听起来像这样。 I need to make a base64 encoded string of a file and for this, I use this method: 我需要对文件进行base64编码的字符串,为此,我使用以下方法:

public String getStringFile(File f) {
    InputStream inputStream = null;
    String encodedFile= "", lastVal;
    try {
        inputStream = new FileInputStream(f.getAbsolutePath());

        byte[] buffer = new byte[10240];
        int bytesRead;

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            output64.write(buffer, 0, bytesRead);
        }

        output64.close();
        encodedFile =  output.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    lastVal = encodedFile;

    return lastVal;
}

and the thing is when I try to encode file something around 20 Mb (exact file size is 19,35 Mb) I get an OutOfMemoryException. 问题是当我尝试对20 Mb左右的文件进行编码(确切的文件大小为19,35 Mb)时,出现OutOfMemoryException。

Before: 之前:

在此处输入图片说明

After: 后:

在此处输入图片说明

What am I doing wrong and how can I fix this issue? 我在做什么错,如何解决此问题? Thanks in advance. 提前致谢。

What am I doing wrong 我究竟做错了什么

You are attempting to encode a ~20MB file using base64 into a string. 您正在尝试使用base64将〜20MB的文件编码为字符串。 You will not have adequate heap space on many Android devices to have a single memory allocation that large. 在许多Android设备上,您将没有足够的堆空间来分配这么大的单个内存。

how can I fix this issue? 我该如何解决这个问题?

If "this issue" is "create a ~26MB string of base64-encoded data", there is no reliable way to do this. 如果“此问题”是“创建〜26MB的base64编码数据字符串”,则没有可靠的方法。 You would have to find some other solution to whatever problem you are trying to solve by creating such a string. 通过创建这样的字符串,您将必须找到要解决的任何问题的其他解决方案。

ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

If you upload the base64 yourself with HttpUrlConnection you can do way with the ByteArrayOutputStream and replace above lines -while directly uploading- with 如果您自己使用HttpUrlConnection上载base64,则可以使用ByteArrayOutputStream并替换上面的行-同时直接上载-

OutputStream output = con.getOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

Untested. 未经测试。

You could also directly base64 encode to a FileOutputStream of course. 当然,您也可以直接将base64编码为FileOutputStream

OutputStream output = new FileOutputStream(......);
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

and then upload that file with POJO. 然后使用POJO上传该文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM