程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用流式传输的Android File To Base64有时会丢失2个字节大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用流式传输的Android File To Base64有时会丢失2个字节?

开发过程中遇到使用流式传输的Android File To Base64有时会丢失2个字节的问题如何解决?下面主要结合日常开发的经验,给出你关于使用流式传输的Android File To Base64有时会丢失2个字节的解决方法建议,希望对你解决使用流式传输的Android File To Base64有时会丢失2个字节有所启发或帮助;

这是在使用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中遭受苦难的人。

解决方法

我写信寻求解决以下困难的正确解决方案:

我需要将文件编码为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.get@R_716_10586@lSpace());

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

大佬总结

以上是大佬教程为你收集整理的使用流式传输的Android File To Base64有时会丢失2个字节全部内容,希望文章能够帮你解决使用流式传输的Android File To Base64有时会丢失2个字节所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。