在阅读时复制Zip文件

问题描述 投票:0回答:1

我正在尝试在读取时复制zip文件,但问题是副本与源不同,即使字节数相同。任何人都可以看到/解释我做错了什么?谢谢!

File fileIn = new File("In.zip");
File fileOut = new File("Out.zip");
final OutputStream out = new FileOutputStream(fileOut);
final AtomicInteger totalBytesRead = new AtomicInteger();
BufferedInputStream copy = new BufferedInputStream(new FileInputStream(fileIn)) {
    @Override
    public synchronized int read(byte[] b, int off, int len) throws IOException {
        int total = super.read(b, off, len);
        if (total != -1) {
            totalBytesRead.addAndGet(total);
            out.write(b, 0, total);
        }
        return total;
    }
};
ZipInputStream zipIn = new ZipInputStream(copy);
ZipEntry zipEntry = null;
while ((zipEntry = zipIn.getNextEntry()) != null) {
    zipIn.closeEntry();
}
IOUtils.copy(copy, new OutputStream() {
    @Override
    public void write(int b) throws IOException {
    }
});
zipIn.close();
out.close();
System.out.println("Expected: " + fileIn.length() + ", Actual: " + totalBytesRead);
System.out.println(FileUtils.contentEquals(fileIn, fileOut));

输出是:

Expected: 3695, Actual: 3695
false
java stream zip compression
1个回答
0
投票

你根本不是在阅读ZIP,你只是枚举它的条目,因此你在阅读过程中也没有复制,并且你在这之后再做一个副本。尝试实际读取zip条目,并删除随后的IOUtils.copy()调用。

© www.soinside.com 2019 - 2024. All rights reserved.