在阅读时复制Zip文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在阅读时复制Zip文件相关的知识,希望对你有一定的参考价值。

我正在尝试在读取时复制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
答案

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

以上是关于在阅读时复制Zip文件的主要内容,如果未能解决你的问题,请参考以下文章

Zip文件在接收时损坏

php代码片段: sendFile/videoStream/sendEmail/phpexcel/ffmpeg/zip

Android:使用支持片段管理器时复制片段

为啥要使用 FrameLayout 作为 FragmentTransaction 的片段容器? [复制]

超实用的php代码片段

将 ZIP 文件提取到绝对路径