You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 1.6中Excel输入流转Base64后解码文件损坏如何解决?

问题根源

你的代码逻辑错误出在Base64编码的数据源选择:

  • 你定义的buffer是读取InputStream时的临时缓冲区,每次循环都会覆盖buffer内的内容
  • 循环读取结束后,buffer里仅保留了最后一次读取到的部分文件字节,而非完整的Excel文件全量字节
  • 你对这个仅存部分内容的buffer做编码,生成的Base64自然不是完整文件的编码结果,解码后得到的文件肯定损坏。

修复方案

修正后的代码示例如下:

URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// 省略响应校验、文件名获取逻辑
InputStream inputStream = httpConn.getInputStream();

String saveFilePath1 = "C:\\test1.xlsx";
String saveFilePath2 = "C:\\test2.xlsx";

// 先把完整流读入字节数组输出流,拿到全量文件字节
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
    baos.write(buffer, 0, bytesRead);
}
byte[] fullFileBytes = baos.toByteArray();

// 测试1:直接写全量字节生成test1,确认文件正常
FileOutputStream outputStream = new FileOutputStream(saveFilePath1);
outputStream.write(fullFileBytes);
outputStream.close();

// 对全量字节做Base64编码
String encodedBytesBase64 = Base64.encodeBase64String(fullFileBytes);

// 测试2:解码后写test2,此时文件可正常打开
FileOutputStream fos = new FileOutputStream(saveFilePath2);
byte[] decodedBytes = Base64.decodeBase64(encodedBytesBase64);
fos.write(decodedBytes);
fos.close();

inputStream.close();
httpConn.disconnect();

如果是JDK 8及以上版本,可以直接使用JDK自带的java.util.Base64工具类,不需要额外引入commons-codec依赖,编码解码写法如下:

  • 编码:String encodedBytesBase64 = Base64.getEncoder().encodeToString(fullFileBytes);
  • 解码:byte[] decodedBytes = Base64.getDecoder().decode(encodedBytesBase64);

内容的提问来源于stack exchange,提问作者Henrique C.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:48:05