JAVA压缩ZIP文件

强颜欢笑 提交于 2020-03-16 09:36:19
public static void main(String[] args) throws IOException
    {
        String path = "F:\\HTML\\PAY";
        String zipFile = "F:\\HTML\\PAY\\zip_"+System.currentTimeMillis()+".zip";
        File dictionary = new File(path);
        
        File[] listFiles = dictionary.listFiles();
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
        zip(path,listFiles,zipOut);
        zipOut.flush();
        zipOut.close();
        System.out.println("Finished");
    }
    
    public static void zip(String root,File[] fileList, ZipOutputStream zipOut) throws IOException
    {
        
        ZipEntry ze = null;
        for (File file : fileList)
        {
            if (file.isDirectory())
            {
                zip(root,file.listFiles(), zipOut);
            }
            else
            {
                // 创建ZipEntry ,设置需加入压缩包的对象名称,为压缩后的文件设置名称
                String fileName = file.getParent().replace(root, "")+File.separator+file.getName();
                if(fileName.startsWith(File.separator)){
                    fileName = fileName.substring(1);
                }
                System.out.println(fileName);
                ze = new ZipEntry(fileName);
                ze.setSize(file.length());
                ze.setTime(file.lastModified());
                // 每一个被压缩的文件都用ZipEntry表示
                zipOut.putNextEntry(ze);
                
                FileInputStream fileInputStream = new FileInputStream(file);
                byte buffer[] = new byte[4096];
                for (int n = 0; -1 != (n = fileInputStream.read(buffer));)
                {
                    zipOut.write(buffer, 0, n);
                }
                fileInputStream.close();
            }
        }
    }

  

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