Reading data from multiple zip files and combining them to one

天大地大妈咪最大 提交于 2019-12-07 16:29:33

问题


I want to read data from lets say 4 zip files called zip1, zip2, zip3, zip4. All of these zip files are split from this 1 big zip file called "BigZip". I want to combine the zip files into one and then compare the bytes if the 1 bigzip file matches the size of bytes with the combined zip file of (zip1+zip2+zip3+zip4). I am getting a very small file size when I combine the size of 4 zip files. What am I doing wrong?

Here is my code for the same:

targetFilePath1, targetFilePath2, targetFilePath3, targetFilePath4 belongs to path of 4 zip files. sourceFilePath is the path to BigZip file

class Test {


public static void main(String args[]) {

ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(sourceBigZip));

            readZip(sourceFilePath, targetFilePath1);
            readZip(sourceFilePath, targetFilePath2);
            readZip(sourceFilePath, targetFilePath3);
            readZip(sourceFilePath, targetFilePath4);
  outStream.close();
}

static void readZip(String sourceBigZip, String targetFile) throws Exception {
    ZipInputStream inStream = new ZipInputStream(new FileInputStream(targetFile));
    byte[] buffer = new byte[1024];
    int len = inStream.read(buffer);
    while (len != -1) {
        outStream.write(buffer, 0, len);
        len = inStream.read(buffer);
        System.out.print(len);
    }

    inStream.close();
}
}

回答1:


Create ZipOutputStream once and pass it to readZip() method, like:

public static void main(String args[]) {
    ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(sourceFilePath));
    readZip(outStream , targetFilePath1);
    readZip(outStream , targetFilePath2);
    readZip(outStream , targetFilePath3);
    readZip(outStream , targetFilePath4);
}

Then you have an error dealing with copying the data from one zip to another... You need to copy each file in the zip file like this:

static void readZip(ZipOutputStream outStream, String targetFile)
        throws Exception {
    ZipInputStream inStream = new ZipInputStream(new FileInputStream(
            targetFile));
    byte[] buffer = new byte[1024];
    int len = 0;

    for (ZipEntry e; (e = inStream.getNextEntry()) != null;) {
        outStream.putNextEntry(e);
        while ((len = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, len);
        }
    }
    inStream.close();
}

}




回答2:


Every time you call new ZipOutputStream, it creates a new empty file, and wipes out everything you have written to it before. You have to create the stream outside of readZip, and pass it in to each call rather than creating a new stream every time.



来源:https://stackoverflow.com/questions/27321825/reading-data-from-multiple-zip-files-and-combining-them-to-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!