Java package multiple files into a Zip file

    /**
     * Compressed into a ZIP file list method * @param srcFiles needs to be compressed
     * @Param out the compressed file output stream
     * @Throws RuntimeException when the compression failure will throw runtime exception
     */
    public static void toZip(List<File> srcFiles , OutputStream out){
        long start = System.currentTimeMillis();
        try (ZipOutputStream zos = new ZipOutputStream(out);) {
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry ();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println ( "compression complete, time-consuming:" + (end - start) + "ms");
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }


Called
public class ClacTest {
    public static void main(String[] args) throws FileNotFoundException {

        ZipFileUtil zf = new ZipFileUtil();
        List<File> files = new ArrayList<File>();
        // Make sure the following files exist
        files.add(new File("E:/res/"+1096251018+"_Bpic.xml"));
        files.add(new File("e:/picture/"+"1096251018-3_"+"o.jpg"));
        files.add(new File("e:/picture/"+"1096251018-1_"+"o.jpg"));
        files.add(new File("e:/picture/"+"1096251018-2_"+"o.jpg"));
        zf.toZip(files,new FileOutputStream(new File("E:/picture.zip")));
    }
}

can

Guess you like

Origin www.cnblogs.com/Koaler/p/12027844.html