您不能将整个文件加载到内存中,如下所示:
byte fileContent[] = new byte[(int) file.length()];
fin.read(fileContent);
而是逐块加载文件并将其分段编码。 Base64是一种简单的编码,一次加载3个字节并对其进行编码就足够了(编码后将产生4个字节)。出于性能原因,请考虑加载 3 个字节的倍数,例如3000 字节 - 应该没问题。还要考虑缓冲输入文件。
一个例子:
byte fileContent[] = new byte[3000];
try (FileInputStream fin = new FileInputStream(file)) {
while(fin.read(fileContent) >= 0) {
Base64.encodeBase64(fileContent);
}
}
请注意,您不能简单地附加结果Base64.encodeBase64()
to encoded
字节数组。实际上,它不是加载文件而是将其编码为 Base64 导致内存不足问题。这是可以理解的,因为 Base64 版本更大(并且您已经有一个占用大量内存的文件)。
考虑将您的方法更改为:
public void encode(File file, OutputStream base64OutputStream)
并将Base64编码的数据直接发送到base64OutputStream
而不是退货。
更新:感谢@史蒂芬C我开发了更简单的版本:
public void encode(File file, OutputStream base64OutputStream) {
InputStream is = new FileInputStream(file);
OutputStream out = new Base64OutputStream(base64OutputStream)
IOUtils.copy(is, out);
is.close();
out.close();
}
It uses Base64OutputStream http://commons.apache.org/codec/api-release/org/apache/commons/codec/binary/Base64OutputStream.html将输入转换为 Base64即时 and IOUtils http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html班级来自Apache 公共 IO http://commons.apache.org/io.
注意:必须关闭FileInputStream
and Base64OutputStream
明确打印=
如果需要,但缓冲由IOUtils.copy()
.