android - 在 Android 上以 Base64 格式转换文件 (<100Mo)

标签 android file base64 android-file

我正在尝试将文件从 sdcard 转换为 Base64,但文件似乎太大,我收到 OutOfMemoryError。

这是我的代码:

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);

在归档 String attachedFile 时有没有办法绕过 OutOfMemoryError?

最佳答案

Base64 编码需要 3 个输入字节并将它们转换为 4 个字节。因此,如果您有 100 Mb 的文件,在 Base64 中最终将达到 133 Mb。当您将它转换为 Java 字符串 (UTF-16) 时,它的大小将加倍。更不用说在转换过程中的某个时刻,您会在内存中保存多个副本。无论你如何转动它,它都很难工作。

这是使用 Base64OutputStream 的稍微优化的代码,需要的内存比您的代码少,但我不会屏住呼吸。我的建议是通过跳过到字符串的转换并使用临时文件流作为输出而不是 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();

关于android - 在 Android 上以 Base64 格式转换文件 (<100Mo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27784230/

相关文章:

java - 在用java编写时限制文件大小

java - sbt 中的工作目录

android - 在 Android 中解码 JSON base64 数据(来自 PHP 的 base64_encode)?

android - 为什么Android版本代码和版本名称一直回到1和1.0?

android - 滚动网格时在 gridview 的情况下重复图像?

Android 覆盖项目

javascript - ReactJS,在 <img> 标签中呈现 base64 字符串给出错误 ERR_INVALID_URL

android - 运算符 == 不能应用于 Kotlin 中的 'Long' 和 'Int'

git - 什么是 BASE、LOCAL、REMOTE 和 cppMerged 文件?

javascript - 显示来自源的 base64 图像 HTML