gpt4 book ai didi

java - Android File To Base64 using streaming 有时会丢失 2 个字节

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:10:36 26 4
gpt4 key购买 nike

我写信是为了寻求解决以下困难的妥善解决方案:

我需要将文件编码为Base64格式,我没有办法把文件变小,所以我肯定会遇到OutOfMemory Exception,所以我使用Streaming的方式来解决它。文件编码后,我立即通过代码和在线工具对其进行了解码。有时会发现解码后的内容在文件末尾缺少 2 个字节,但并非总是如此。它确实影响了对文件的进一步处理。

希望有人能提供帮助,并且可能是由一个愚蠢的错误引起的。还是谢谢。

代码如下:

FileOutputStream fout = new FileOutputStream(path + ".txt");
//this is for printing out the base64 content
FileInputStream fin = new FileInputStream(path);

System.out.println("File Size:" + path.getTotalSpace());

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

String result = new String(os.toByteArray(), "UTF-8");

fout.write(os.toByteArray());
fout.close();
base64out.close();
os.close();
fin.close();

return result;

最佳答案

这是在使用 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;

实际上,在使用 Dawnkeeper 的建议添加 flush() 后,我只移动了一行代码。这些技巧是在处理任何数据之前在 base64out.close() 中完成的。由于关闭 Base64OutputStream 可能会将 Base64 的结束填充写入输出。我的想法来自 org.apache.myfaces.trinidad.util.Base64OutputStream关闭()方法。这就是我尝试的原因。

在数据处理之前关闭 OutputStream 可能看起来很奇怪,但在这种情况下它只关闭 Base64OutputStream 而不是同时关闭 ByteArrayOutputStream。因此,数据仍然可以从 ByteArrayOutputStream 中检索。

感谢 Dawnkeeper 的努力,并希望这个问题可以帮助其他遭受 OutOfMemory Exception 的人。

关于java - Android File To Base64 using streaming 有时会丢失 2 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24798745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com