我有用于测试简单 xlsx 文件副本的类
public static void main(String[] args) throws Exception {
FileWriter fileWriter = new FileWriter("Classeur2.xlsx");
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(new String(Files.readAllBytes(Paths.get("Classeur1.xlsx"))));
printWriter.close();
byte[] bytes = new byte[150];
System.out.println("++ Classeur1.xlsx ++++++++++++++++++++++");
System.out.println(new String(Files.readAllBytes(Paths.get("Classeur1.xlsx"))).substring(0,150));
System.arraycopy(Files.readAllBytes(Paths.get("Classeur1.xlsx")), 0, bytes, 0, 150);
System.out.println(Arrays.toString(bytes));
System.out.println("++ Classeur2.xlsx ++++++++++++++++++++++");
System.out.println(new String(Files.readAllBytes(Paths.get("Classeur2.xlsx"))).substring(0,150));
System.arraycopy(Files.readAllBytes(Paths.get("Classeur2.xlsx")), 0, bytes, 0, 150);
System.out.println(Arrays.toString(bytes));
}
Classeur1.xlsx
文件正常打开。 Classeur2.xlsx
文件无法打开(文件已损坏)。
运行时的输出
++ Classeur1.xlsx ++++++++++++++++++++++
PK ! b�h^ � [Content_Types].xml �(�
[80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33, 0, 98, -18, -99, 104, 94, 1, 0, 0, -112, 4, 0, 0, 19, 0, 8, 2, 91, 67, 111, 110, 116, 101, 110, 116, 95, 84, 121, 112, 101, 115, 93, 46, 120, 109, 108, 32, -94, 4, 2, 40, -96, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
++ Classeur2.xlsx ++++++++++++++++++++++
PK ! b�h^ � [Content_Types].xml �(�
[80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33, 0, 98, -17, -65, -67, 104, 94, 1, 0, 0, -17, -65, -67, 4, 0, 0, 19, 0, 8, 2, 91, 67, 111, 110, 116, 101, 110, 116, 95, 84, 121, 112, 101, 115, 93, 46, 120, 109, 108, 32, -17, -65, -67, 4, 2, 40, -17, -65, -67, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
第15个字节之后似乎有区别。是编码的问题吗? 我不知道源文件编码(它可以有多个来源并通过电子邮件发送给我)。解决办法是什么?
使用InputStream读取数据,然后使用OutputStream写入数据。 要将数据从 InputStream 传输到 OutputStream,请使用字节数组。
代码可能如下所示:
try(InputStream in = new FileInputStream(...); OutputStream out = new FileOutputStream(...)) {
byte[] buffer = new byte[];
int read = in.read(buffer);
while (read >=0) {
out.write(buffer, 0, read);
read = in.read(buffer);
}
}