java 实现本地文件的压缩、删除

1.先得到本地文件所在目录;
2.判断该目录下是否有文件存在,for循环得到目录下的文件;
3.对文件进行压缩;(只保留4天的压缩文件内容)
4.对文件进行删除;

//压缩方法
    /**
         * 压缩成ZIP 方法1
         * @param srcDir 压缩文件夹路径
         * @param out    压缩文件输出流
         * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
         *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
         * @throws RuntimeException 压缩失败会抛出运行时异常
         */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
        throws RuntimeException{
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            //String fileDir=srcDir.substring(0,srcDir.lastIndexOf("/"));
            File sourceFile = new File(srcDir);
            compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  /**
         * 递归压缩方法
         * @param sourceFile 源文件
         * @param zos        zip输出流
         * @param name       压缩后的名称
         * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
         *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
         * @throws Exception
         */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            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);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if(KeepDirStructure){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            }else {

                for (File file : listFiles) {
                    String date= String.valueOf(Integer.parseInt(Machine.getSystemDate())-1);
//  如果后缀是zip不压缩
//                  if(!file.getName().contains("zip")) {
                        // 判断是否需要保留原来的文件结构
//                        if(file.getName().contains(date)) {
                            if (KeepDirStructure) {
                                // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                                // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                                compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                            } else {
                                compress(file, zos, file.getName(), KeepDirStructure);
                            }
                        }
//                    }
//                }
            }
        }
    }

删除方法

//删除文件

    public static boolean delAllFile(String path) throws Exception {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                String date=Machine.getPreDateTime(-1).get("SystemDate");//获取系统日期的前一天
                if ((temp.getPath().contains("zip"))) {
                        int startNum = Integer.parseInt(Machine.getPreDateTime(-4).get("SystemDate"));//获取系统日期的前4天
                        int endNum = Integer.parseInt(Machine.getSystemDate());//系统日期
                        //对目录进行字符串截取
                        int index = tempList[i].indexOf("_");
                        int pathDate = Integer.parseInt(tempList[i].substring(0, index));//截取到目录日期
                        if (pathDate < startNum || pathDate > endNum) {
                            temp.delete();
                        }else if(pathDate >=endNum){
                            temp.delete();
                        }
                        if((pathDate==endNum)){
                            temp.delete();
                        }
                        if(temp.getPath().contains("ALL")){
                            continue;
                        }

                    } else {
                        temp.delete();
                    }

//                }
            }
            if (temp.isDirectory()) {
                String paths=temp.getPath().replace("\\","/");
                //ALL为同级目录下的文件夹,该文件夹不删除
                if (!paths.equals("D:/csv/ALL")) {
                    delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                    delFolder(path + "/" + tempList[i]);//再删除空文件夹
                    flag = true;
                }
            }
        }
        return flag;
    }

main方法测试

  public static void main(String[] args) {
        try {
            String allName = null;
            File files = new File("D:/csv/pro");//创建文件对象,url是目标目录
            String date= Machine.getPreDateTime(-1).get("SystemDate");//获取当前日期的前一天
            if (files.exists()) { //目录是否存在
                File[] files2 = files.listFiles();// 读取文件夹下的所有文件
                int m = 0, n = 0;
                for (int i = 0; i < files2.length; i++) {
                    if (files2[i].isFile()) { //判断是否是文件
                        if (files2[i].getName().contains("zip")) {
                            continue;
                        }
                            m++;
                            System.out.println("第" + m + "个文件的名字是:" + files2[i].getName());
                        } else {
                            n++;
                            System.out.println("第" + n + "个目录的名字是:" + files2[i].getName());
                            if (files2[i].getName().equals("ALL")) {
                                File[] allFiles = files2[i].listFiles();// 读取文件夹下的所有文件
                                for (int j = 0; j < allFiles.length; j++) {
                                    System.out.println(allFiles[j].getName());
                                    allName = allFiles[j].getName();
                                }
                            } else {
                                allName = files2[i].getName();
                            }

                    }

                    //得到本地文件目录
                    String filename="D:/csv/pro/"+date;
                    if(files2[i].getName().equals(date)) {
                        ZipUtils zipUtils = new ZipUtils();
                        OutputStream out = new FileOutputStream("D:/csv/pro/" + date + "_bak.zip");
                        // 压缩文件
                        ZipUtils.toZip("D:/csv/pro/" + date, out, true);
                        //删除文件
                        ZipUtils.delAllFile("D:/csv/pro/");
//                        File dirFile = new File("D:/csv/pro/" + date);
//
//                        deleteDirectory(dirFile);

                    }
                     if(allName.equals(date)){
                        ZipUtils zipUtils = new ZipUtils();
                        OutputStream  out=new FileOutputStream("D:/csv/pro/ALL/"+date+"_bak.zip");
                        // 压缩文件
                        ZipUtils.toZip("D:/csv/pro/ALL/"+date,  out, true);
                        //删除文件
                        ZipUtils.delAllFile("D:/csv/pro/ALL/");
//                         File dirFile =new File("D:/csv/pro/ALL/"+date);
//
//                         deleteDirectory(dirFile);
                    }

                }
            } else {
                System.out.println("文件不存在");

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

获取前几天的日期:

 //获取指定日期 index为下标,如:昨天日期为-1,前两天的日期为-2
 //对该方法的调用:String date=Machine.getPreDateTime(-1).get("SystemDate");
    public static HashMap<String, String> getPreDateTime(int index) throws Exception{
        String str_SystemDate = null;
        String str_SystemTime = null;
        String str_month = null;
        String str_date = null;
        HashMap<String, String> htl_SystemDateTime = new HashMap<String, String>();
        try {
            Calendar obj_calendar = Calendar.getInstance();
            obj_calendar.add(Calendar.DAY_OF_MONTH, index);
            obj_calendar.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            /* 取得系統日期 格式: yyyymmdd */
            if ((obj_calendar.get(Calendar.MONTH) + 1) < 10) {
                str_month = "0" + (obj_calendar.get(Calendar.MONTH) + 1);
            } else {
                str_month = String.valueOf(obj_calendar.get(Calendar.MONTH) + 1);
            }

            if (obj_calendar.get(Calendar.DATE) < 10) {
                str_date = "0" + obj_calendar.get(Calendar.DATE);
            } else {
                str_date = String.valueOf(obj_calendar.get(Calendar.DATE));
            }

            str_SystemDate = obj_calendar.get(Calendar.YEAR) + str_month + str_date;

            /* 取得系統時間 格式(24小時進制): hhmmss */
            String str_hour = null;
            String str_minute = null;
            String str_second = null;

            if (obj_calendar.get(Calendar.HOUR) < 10 && obj_calendar.get(Calendar.AM_PM) == Calendar.AM) {
                str_hour = "0" + obj_calendar.get(Calendar.HOUR);
            } else if (obj_calendar.get(Calendar.AM_PM) == Calendar.PM) {
                str_hour = String.valueOf(obj_calendar.get(Calendar.HOUR) + 12);
            } else {
                str_hour = String.valueOf(obj_calendar.get(Calendar.HOUR));
            }

            if (obj_calendar.get(Calendar.MINUTE) < 10) {
                str_minute = "0" + obj_calendar.get(Calendar.MINUTE);
            } else {
                str_minute = String.valueOf(obj_calendar.get(Calendar.MINUTE));
            }

            if (obj_calendar.get(Calendar.SECOND) < 10) {
                str_second = "0" + obj_calendar.get(Calendar.SECOND);
            } else {
                str_second = String.valueOf(obj_calendar.get(Calendar.SECOND));
            }

            str_SystemTime = str_hour + str_minute + str_second;

            htl_SystemDateTime.put("SystemDate", str_SystemDate);
            htl_SystemDateTime.put("SystemTime", str_SystemTime);
            return htl_SystemDateTime;
        } catch (Exception e) {
            throw new Exception("get SystemDateTime error");
        }

    }

压缩之前的文件夹:
在这里插入图片描述
在这里插入图片描述
压缩以后:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值