Java 中的 ZipOutputStream 压缩流的使用

参考学习

https://blog.csdn.net/u013087513/article/details/52151227

https://blog.csdn.net/z69183787/article/details/8290811

https://www.cnblogs.com/zeng1994/p/7862288.html

package zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFile {

    public void zip(String filepath,String zippath) throws IOException {
        File fs = new File(filepath);
        ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(zippath));
        zo.setComment("多文件压缩");
        recursionZip(fs,zo,"");
        zo.close();
    }
    private void recursionZip(File fs,ZipOutputStream zo,String baseDir) throws IOException {
        if(fs.isDirectory()) {
            File[] ff = fs.listFiles();
            if(ff.length==0) {
                zo.putNextEntry(new ZipEntry(baseDir + fs.getName()+File.separator));
                zo.closeEntry();
            }
            for(File f : ff) {
                recursionZip(f,zo,baseDir + fs.getName() + File.separator);
            }
        }else {
            byte[] b = new byte[1024];
            zo.putNextEntry(new ZipEntry(baseDir + fs.getName()));
            FileInputStream fi = new FileInputStream(fs);
            int len = 0;
            while((len = fi.read(b))!=-1) {
                zo.write(b,0,len);
            }
            fi.close();
            zo.closeEntry();
        }
    }
    public static void main(String[] args) {
        String filepath = "d:"+ File.separator + "hello";
        String zippath = "d:" + File.separator + "hello.zip";
        ZipFile zf = new ZipFile();
        try {
            zf.zip(filepath,zippath);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.51cto.com/maplebb/2158495
今日推荐