android使用zip压缩文件。

这段代码提供了两个Java方法,分别用于压缩单个文件和整个目录。压缩过程使用了ZipOutputStream,对指定路径的文件或目录进行读取,然后写入到压缩文件中。如果指定过滤,只会压缩在特定时间之后修改的文件。
摘要由CSDN通过智能技术生成

1、压缩文件

 /**
     * 压缩文件
     *
     * @param sourceFile  待压缩的源文件路径
     * @param zipFilePath 压缩文件保存路径
     * @param zipFileName 压缩文件名
     * @return 压缩成功返回true
     */
    public static boolean compressFile(String sourceFile, String zipFilePath, String zipFileName) {
        //压缩文件的路径
        File zipFile = new File(zipFilePath + zipFileName);
        if (zipFile.exists()) {
            return false;
        }

        File zipFileFolder = new File(zipFilePath);
        if (!zipFileFolder.exists()) {
            return false;
        }

        File file = new File(sourceFile);
        FileInputStream fis = null;
        ZipOutputStream zos = null;
        try {
            fis = new FileInputStream(file);
            zos = new ZipOutputStream(new FileOutputStream(zipFilePath + zipFileName));

            // 创建压缩文件中的条目
            ZipEntry entry = new ZipEntry(file.getName());

            // 将创建好的条目加入到压缩文件中
            zos.putNextEntry(entry);
            // 写入当前条目所对应的具体内容
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = fis.read(buff)) != -1) {
                zos.write(buff, 0, len);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                zos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Log.d(TAG, "compressFile==>success");
        return true;
    }

2、压缩目录

  /**
     * @param sourceFile
     * @param zipFilePath
     * @param zipFileName
     * @param isFilter
     * @param time        过滤时间,一般是当前日期的零点的时间戳
     * @return
     */
    public static boolean compressDir(String sourceFile, String zipFilePath, String zipFileName, boolean isFilter, long time) {
        //压缩文件的路径
        File zipFile = new File(zipFilePath + zipFileName);
        if (zipFile.exists()) {
            return false;
        }

        File zipFileFolder = new File(zipFilePath);
        if (!zipFileFolder.exists()) {
            return false;
        }

        File fileDir = new File(sourceFile);
        if (!fileDir.isDirectory()) {
            return false;
        }
        File[] files = fileDir.listFiles();
        if (files == null || files.length == 0) {
            return false;
        }
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFilePath + zipFileName));
            if (isFilter) {
                FileInputStream in = null;
                for (File srcFile : files) {
                    try {
                        long lastModified = srcFile.lastModified();
                        //最后修改大于过滤时间的才打包,防止该目录下文件过多,过大
                        if (lastModified > time) {
                            byte[] buf = new byte[1024];
                            zos.putNextEntry(new ZipEntry(srcFile.getName()));
                            int len;
                            in = new FileInputStream(srcFile);
                            while ((len = in.read(buf)) != -1) {
                                zos.write(buf, 0, len);
                            }
                        }
                    } catch (Exception e) {

                    } finally {
                        try {
                            zos.closeEntry();
                            if (in != null)
                                in.close();
                            in = null;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                FileInputStream in = null;
                for (File srcFile : files) {
                    try {
                        byte[] buf = new byte[1024];
                        zos.putNextEntry(new ZipEntry(srcFile.getName()));
                        int len;
                        in = new FileInputStream(srcFile);
                        while ((len = in.read(buf)) != -1) {
                            zos.write(buf, 0, len);
                        }
                    } catch (Exception e) {

                    } finally {
                        try {
                            zos.closeEntry();
                            if (in != null)
                                in.close();
                            in = null;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                zos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Log.d(TAG, "compressFile==>success");
        return true;
    }

3、

//sdk 26以上用
    @RequiresApi(api = Build.VERSION_CODES.O)
    void compressDir() {
        Path filepath = Paths.get("E:\\siniSVN\\res\\AAMS-V10");//目标文件夹
        String zipname = "D:\\abcd.zip";//目标输出路径
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipname))) {
            Files.walkFileTree(filepath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    ZipEntry dirEntry = new ZipEntry(this.replaceRootDir(dir) + "/");
                    zipOutputStream.putNextEntry(dirEntry);
                    zipOutputStream.closeEntry();
                    return super.preVisitDirectory(dir, attrs);
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    zipFile(file);
                    return super.visitFile(file, attrs);
                }

                private Path replaceRootDir(Path dir) {
                    Path subpath = dir.subpath(filepath.getParent().getNameCount(), dir.getNameCount());
                    return subpath;
                }

                private void zipFile(Path file) throws IOException {
                    Path subPath = replaceRootDir(file);
                    //文件压缩
                    ZipEntry zipEntry = new ZipEntry(subPath.toString());
                    zipOutputStream.putNextEntry(zipEntry);
                    try (BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(file.toFile()))) {
                        byte[] buffer = new byte[1024];
                        while (fileInputStream.read(buffer) != -1) {
                            zipOutputStream.write(buffer);
                        }
                        zipOutputStream.closeEntry();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值