尝试使用 BufferedInputStream 和 Base64 在 Java 中对大文件进行编码

问题描述

我是 Java I/O 的新手,所以请帮忙。

我正在尝试使用 apache commons 库处理一个大文件(例如 50mb 的 pdf 文件)。 起初我尝试:

byte[] bytes = FileUtils.readFileToByteArray(file);
String encodeBase64String = Base64.encodeBase64String(bytes);
byte[] decoded = Base64.decodeBase64(encodeBase64String);

但是知道 org.apache.commons.io 中的 FileUtils.readFileToByteArray 会将整个文件加载到内存中,我尝试使用 BufferedInputStream 逐个读取文件:

BufferedInputStream bis = new BufferedInputStream(inputStream);
StringBuilder pdfStringBuilder = new StringBuilder();
int byteArraySize = 10;
byte[] tempByteArray = new byte[byteArraySize];
while (bis.available() > 0) {
                if (bis.available() < byteArraySize) { // reaching the end of file
                    tempByteArray = new byte[bis.available()];
                }
                int len = Math.min(bis.available(),byteArraySize);
                read = bis.read(tempByteArray,len);

                if (read != -1) {
                    pdfStringBuilder.append(Base64.encodeBase64String(tempByteArray));
                } else {
                    System.err.println("End of file reached.");
                }
            }
byte[] bytes = Base64.decodeBase64(pdfStringBuilder.toString());

然而,2个解码后的字节数组看起来不太一样... ...实际上,只给出了10个字节,这是我的临时数组大小... ...

任何人都可以帮忙:

  • 逐个读取文件我做错了什么?
  • 为什么解码后的字节数组在第二个解决方案中只返回 10 个字节?

提前致谢:)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)