How to create a zip file of multiple image files

前端 未结 2 1103
猫巷女王i
猫巷女王i 2020-12-09 12:09

I am trying to create a zip file of multiple image files. I have succeeded in creating the zip file of all the images but somehow all the images have been hanged to 950 byt

相关标签:
2条回答
  • 2020-12-09 12:45

    Change this:

    while((length=fin.read())>0)
    

    to this:

    while((length=fin.read(b, 0, 1024))>0)
    

    And set buffer size to 1024 bytes:

    b=new byte[1024];
    
    0 讨论(0)
  • 2020-12-09 12:46

    This is my zip function I always use for any file structures:

    public static File zip(List<File> files, String filename) {
        File zipfile = new File(filename);
        // Create a buffer for reading the files
        byte[] buf = new byte[1024];
        try {
            // create the ZIP file
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
            // compress the files
            for(int i=0; i<files.size(); i++) {
                FileInputStream in = new FileInputStream(files.get(i).getCanonicalName());
                // add ZIP entry to output stream
                out.putNextEntry(new ZipEntry(files.get(i).getName()));
                // transfer bytes from the file to the ZIP file
                int len;
                while((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                // complete the entry
                out.closeEntry();
                in.close();
            }
            // complete the ZIP file
            out.close();
            return zipfile;
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
        return null;
    }
    
    0 讨论(0)
提交回复
热议问题