手记

Java 中的 ZipOutputStream 压缩流的使用


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()+"/"));                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();        }    }}

0人推荐
随时随地看视频
慕课网APP