【发布时间】:2023-03-21 20:50:01
【问题描述】:
我是base64编码一个excel文件,把它发送到保存它的地方。显然在此之后,excel抱怨文件不正确,如果我想尝试恢复。我正在做的代码(其实我做了一个快速测试main方法)是:
public static void main(String[] args) throws IOException {
Path p = Paths.get("C:\\VariousJunk\\excel-test", "test.xlsx");
ByteArrayOutputStream base64StringOutputStream = new ByteArrayOutputStream();
OutputStream base64EncodingStream = Base64.getEncoder().wrap(base64StringOutputStream);
Files.copy(p, base64EncodingStream);
base64StringOutputStream.close();
String b64 = base64StringOutputStream.toString();
byte[] data = Base64.getDecoder().decode(b64);
FileOutputStream fos = new FileOutputStream("C:\\VariousJunk\\excel-test\\test-backup.xlsx");
fos.write(data);
fos.close();
}
现在我比较了两个文件的二进制数据,结果显示输出文件只缺少最后一个值为 0 的字节。我添加了最后一位进行测试
fos.write(data);
fos.write(0);
fos.close();
而且效果很好。问题是我将把它用于任何其他类型的数据,所以我不确定硬编码最后一个字节是否是个好主意,可能会导致其他文件类型崩溃。这是这种 Base64 编码方法的特性还是我做错了什么?
【问题讨论】:
-
From the API - 在
base64StringOutputStream.toString()之前可能需要base64StringOutputStream.close()。 -
@AndrewS 我已经修改了上面的示例以添加关闭,但仍然缺少最后一个字节