JAVA puts the specified file into the compressed package

/**
     * 测试多个文件放入压缩包
     * @param args
     */
    public static void main(String[] args) {

        Map<String, File> srcfile = new HashMap<String, File>(){
   
   {
            //key为压缩后的名称(随便起),  value为被压缩的文件的全路径
            put("1.pdf", new File("D:\\wenjian\\test\\test.pdf"));
            put("2.xls", new File("D:\\wenjian\\test\\test1.xls"));
        }};

        //压缩后存储的全路径
        String url = "D:\\wenjian\\test\\cs\\"+ "abc.zip";
        zipFiles(srcfile, new File(url));
    }


    public static void zipFiles(Map<String, File> srcfile, File zipfile) {
        byte[] buf = new byte[10240];
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile))) {

            srcfile.forEach((key, value) -> {
                try {
                    try (FileInputStream in = new FileInputStream(value)) {
                        out.putNextEntry(new ZipEntry(key));
                        int len;
                        while ((len = in.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                        out.closeEntry();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Results of the:
insert image description here

After opening the compressed package, there are two files just put in↓
insert image description here

Guess you like

Origin blog.csdn.net/weixin_42915457/article/details/114928539