使用ZipOutputStream自定义一个压缩文件

一.先确定一下压缩文件步骤

1. 创建一个压缩包。一般是原filename + “.zip”
2. 读取源文件,并把源文件输出到压缩包中
3. 把创建好的压缩包输出到硬盘的指定位置

二.代码实现

1. 读取源文件,并把源文件输出到压缩包中

注意:
1.源文件可能是文件也可能是文件夹,要进行不同的处理
2.使用BufferedInputStream读取源文件,使用ZipOutStream输出成压缩文件

 	public static void  createZIP(File filepath, ZipOutputStream zos,String filename){
        //判断是否是文件夹
        if (filepath.isDirectory()){
            //创建文件夹下对应的文件类
            File[] files = filepath.listFiles();
            filename = filename +"\\";

            try {
                //对空的文件夹进行处理
                zos.putNextEntry(new ZipEntry(filename));
                for (File file : files) {
                    //递归分解文件夹
                    createZIP(file,zos,file.getName());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else{
            BufferedInputStream bis = null;
            //如果是文件直接进行压缩
            try {
                bis = new BufferedInputStream(new FileInputStream(filepath));
                //创建一个一个文件夹放压缩文件
                zos.putNextEntry(new ZipEntry(filename));
                byte[] bytes = new byte[1024];
                int len;
                //读取文件并压缩
                while((len= bis.read(bytes))!=-1){
                    zos.write(bytes,0,len);
                }

            } catch (Exception e) {
                e.printStackTrace();

            }finally {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

2.确定压缩包名和压缩包存储路径

	public static void createZIPFile(String filepath,String targetPath){

        //需要压缩的文件
        File file = new File(filepath);

        //压缩文件后的位置
        File target = new File(targetPath);
        String targetName = "";
        //确定压缩文件名
        if (!file.isDirectory()){
            System.out.println(file.getName().split("\\.")[0]);
            targetName = file.getName().split("\\.")[0]+".zip";

        }else {
            targetName = file.getName() +".zip";
        }
        //确定压缩后文件的位置
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            fos = new FileOutputStream(targetPath+"\\"+targetName);
            zos = new ZipOutputStream(fos);
            createZIP(file,zos,"");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

3.调用方法生成压缩文件

    private  String  filepath = "D:\\360安全浏览器下载";
    private  String  targetPath = "D:\\迅雷下载";
    @Test
    public void fun(){
        try {
            createZIPFile(filepath,targetPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(新姿势)