java zip压缩文件

此博客围绕Java进行文件ZIP压缩展开,虽未给出具体内容,但核心是利用Java语言实现文件的ZIP压缩操作,属于后端开发中Java技术的应用。
package com.jcjt.download.utils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;


/**
  * 压缩文件操作类 <br>
  */
public class ZipUtils {
    private static final int  BUFFER_SIZE = 2 * 1024;

    public static void toZip(String srcDir, OutputStream out) throws RuntimeException{
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile,zos,sourceFile.getName());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(zos != null){
                    zos.flush();
                    zos.close();
                }
            }catch (Exception e){
                throw new RuntimeException("ZIP流关闭失败");
            }
        }
    }

    private static void compress(File sourceFile, ZipOutputStream zos, String name) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            //一定要设置GBK否则下载后zip内部文件中文乱码
            zos.setEncoding("GBK");
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        }else{
            File[] listFiles = sourceFile.listFiles();
            for (File file : listFiles){
                compress(file, zos, name + "/" + file.getName());
            }
        }
    }

    //删除源文件 
    public static void deleteSourceFile(File sourceFile){
        if(sourceFile.exists()){
            if(sourceFile.isFile()){
                sourceFile.delete();
            }else {
                File[] files = sourceFile.listFiles();
                for(File file : files){
                    deleteSourceFile(file);
                }
                sourceFile.delete();
            }
        }else {
            System.out.println("文件不存在!");
        }
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值