小编典典
这是在使用Base64OutputStream的情况下有效的解决方案。我将在代码后解释其中的一些:
这是代码:
FileOutputStream fout = new FileOutputStream(path + ".txt");
FileInputStream fin = new FileInputStream(path);
System.out.println("File Size:" + path.length());
ByteArrayOutputStream os = new ByteArrayOutputStream();
Base64OutputStream base64out = new Base64OutputStream(os,Base64.NO_WRAP);
byte[] buffer = new byte[3 * 512];
int len = 0;
while ((len = fin.read(buffer)) >= 0) {
base64out.write(buffer, 0, len);
}
System.out.println("Encoded Size:" + os.size());
base64out.flush();
base64out.close();//this did the tricks. Please see explanation.
String result = new String(os.toByteArray(), "UTF-8");
fout.write(os.toByteArray());
fout.flush();
fout.close();
os.close();
fin.close();
return result;
实际上,在通过添加flush()使用Dawnkeeper的建议之后,我只移动了一行代码。这些技巧是在处理任何数据之前在base64out.close()中完成的。关闭Base64OutputStream时,可能会将Base64的结尾填充写入输出。我的想法来自org.apache.myfaces.trinidad.util.Base64OutputStream
close()方法。这就是为什么我尝试。
在数据处理之前关闭OutputStream似乎很奇怪,但是在这种情况下,它仅同时关闭Base64OutputStream而不同时关闭ByteArrayOutputStream。因此,数据仍然可以从ByteArrayOutputStream中检索。
感谢Dawnkeeper的努力,并希望这个问题可以帮助其他在OutOfMemory Exception中遭受苦难的人。
2020-11-01