您不能像下面这样将整个文件加载到内存中:
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.enprebase64(fileContent); }}请注意,您不能简单地将结果附加
base64.enprebase64()到
enpredbbyte数组。实际上,它没有加载文件,而是将其编码为base64,从而导致内存不足的问题。这是可以理解的,因为base64版本更大(并且您已经有一个占用大量内存的文件)。
考虑将您的方法更改为:
public void enpre(File file, OutputStream base64OutputStream)
并将base64编码的数据直接发送到
base64OutputStream而不是将其返回。
更新:感谢 @StephenC, 我开发了更简单的版本:
public void enpre(File file, OutputStream base64OutputStream) { InputStream is = new FileInputStream(file); OutputStream out = new base64OutputStream(base64OutputStream) IOUtils.copy(is, out); is.close(); out.close();}它使用
base64OutputStream它将输入 实时
转换为base64
以及
IOUtils来自Apache
Commons IO的类。
注意:如果需要,您必须关闭
FileInputStream和
base64OutputStream显式打印
=,但是缓冲由处理
IOUtils.copy()。



