转换的文件(小于100Mo)以Base64在Android [英] Convert a file (<100Mo) in Base64 on Android

查看:259
本文介绍了转换的文件(小于100Mo)以Base64在Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将文件从SD卡为Base64转换,但似乎该文件是太大,我得到一个OutOfMemoryError。

I am trying to convert a file from the sdcard to Base64 but it seems the file is too big and i get an OutOfMemoryError.

下面是我的code:

InputStream inputStream = null;//You can get an inputStream using any IO API
inputStream = new FileInputStream(file.getAbsolutePath());
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
    }
} catch (IOException e) {
    e.printStackTrace();
}
bytes = output.toByteArray();
attachedFile = Base64.encodeToString(bytes, Base64.DEFAULT);

有没有办法绕过去的,而OutOfMemoryError异常立案字符串attachedFile?

Is there a way to go around the OutOfMemoryError while filing the String attachedFile ?

推荐答案

的Base64 编码需要3个输入字节,并将其转换为4个字节。所以,如果你有100 MB的文件,将最终将在的Base64 133兆。当你将其转换为Java字符串( UTF-16 ),它的大小将增加一倍。且不说期间的某个点转换过程中你会在内存中保留的多个副本。不管你怎么把这个它很难去上班。

Base64 encoding takes 3 input bytes and converts them to 4 bytes. So if you have 100 Mb file that will end up to be 133 Mb in Base64. When you convert it to Java string (UTF-16) it size will be doubled. Not to mention that during conversion process at some point you will hold multiple copies in memory. No matter how you turn this it is hardly going to work.

使用 Base64OutputStream ,将需要比你的code内存少了,但我不认为我的呼吸这是稍微更优化code。我的建议是通过跳过转换为字符串,并使用临时文件流作为输出,而不是进一步提高了code ByteArrayOutputStream

This is slightly more optimized code that uses Base64OutputStream and will need less memory than your code, but I would not hold my breath. My advice would be to improve that code further by skipping conversion to string, and using temporary file stream as output instead of ByteArrayOutputStream.

InputStream inputStream = null;//You can get an inputStream using any IO API
inputStream = new FileInputStream(file.getAbsolutePath());
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
try {
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        output64.write(buffer, 0, bytesRead);
    }
} catch (IOException e) {
    e.printStackTrace();
}
output64.close();

attachedFile = output.toString();

这篇关于转换的文件(小于100Mo)以Base64在Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆