JAVA Zip压缩 Tar压缩 tar.gz打包压缩

直接上代码:

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.4.1</version>
        </dependency>


import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Rorschach
 * @title: TestAll
 * @description: TODO
 * @date 2019-05-229:40
 */
public class CompressUtil {
    private String zipFileName;      // 目的地Zip文件
    private String sourceFileName;   //源文件(带压缩的文件或文件夹)
    private static Logger logger = Logger.getLogger(CompressUtil.class.getName());

    public CompressUtil() {
    }

    public CompressUtil(String zipFileName, String sourceFileName) {
        this.zipFileName = zipFileName;
        this.sourceFileName = sourceFileName;
    }

    /**
     * @description: 遍历文件夹,对归档好的文件夹进行压缩
     * @author Rorschach
     * @date 2019-05-23 15:55
     */
    public void fullTar(String tempDir) throws Exception {
        String path = getPath(tempDir);
        File allFile = new File(path);
        File[] files = allFile.listFiles();
        String resultName = "";
        for (File file : files) {
            resultName = path + "\\" + file.getName() + ".tar";
            new CompressUtil(resultName, path + "\\" + file.getName() + "\\").tar();
            gzipCompression(resultName, resultName + ".gz");
        }
    }

    /**
     * @description: 获取包含了归档好的文件的路径
     * @author Rorschach
     * @date 2019-05-23 15:54
     */
    public String getPath(String path) {
        File allFile = new File(path);
        File[] files = allFile.listFiles();
        String dirPath = "";
        for (int i = 0; i < files.length; i++) {
            logger.info(files[i].getName());
            if (files[i].isDirectory() && files[i].getName().startsWith("RADA_ST_DOR_L2_CAP")) {
                logger.info("true");
                dirPath = files[i].getParent();
                break;
            } else {
                String rs = getPath(files[i].getPath());
                if (rs != null && !"".equals(rs)) {
                    return rs;
                }
            }
        }
        if (dirPath.length() != 0) {
            return dirPath;

        } else {
            return "没有找到目录";
        }

    }

    /**
     * @description: zip压缩
     * @author Rorschach
     * @date 2019-05-23 15:54
     */
    public void zip() throws Exception {
        //File zipFile = new File(zipFileName);
        logger.info("压缩中...");
        ZipOutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            //创建zip输出流
            out = new ZipOutputStream(new FileOutputStream(zipFileName));
            File sourceFile = new File(sourceFileName);
            //调用函数
            compress(out, sourceFile, sourceFile.getName());

        } catch (Exception e1) {
            logger.info("压缩异常!!!!!!!!!请联系系统管理员");
            e1.printStackTrace();
        } finally {
            if (bos != null)
                bos.close();
            if (out != null)
                out.close();
        }

        System.out.println("压缩完成");

    }

    /**
     * @description: tar压缩
     * @author Rorschach
     * @date 2019-05-23 15:53
     */
    public void tar() throws Exception {
        //File zipFile = new File(zipFileName);
        logger.info("tar压缩中...");
        TarArchiveOutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            //创建tar输出流
            out = new TarArchiveOutputStream(new FileOutputStream(zipFileName), 512000);
            File sourceFile = new File(sourceFileName);
            //调用函数
            tarCompress(out, sourceFile, sourceFile.getName());

        } catch (Exception e1) {
            logger.info("压缩异常!!!!!!!!!请联系系统管理员");
            e1.printStackTrace();
        } finally {

            if (out != null)
                out.close();
            if (bos != null)
                bos.close();
        }

        System.out.println("压缩完成");

    }

    /**
     * @description: zip压缩
     * @author Rorschach
     * @date 2019-05-23 15:53
     */
    public void compress(ZipOutputStream out, File sourceFile, String base) throws Exception {
        //如果路径为目录(文件夹)
        if (sourceFile.isDirectory()) {
            //取出文件夹中的文件(或子文件夹)
            File[] flist = sourceFile.listFiles();
            if (flist.length == 0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
            {
                System.out.println(base + "/");
                out.putNextEntry(new ZipEntry(base + "/"));
            } else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
            {
                for (int i = 0; i < flist.length; i++) {
                    compress(out, flist[i], base + "/" + flist[i].getName());
                }
            }
        } else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入tar文件中
        {
            out.putNextEntry(new ZipEntry(base));
            FileInputStream fos = new FileInputStream(sourceFile);
            BufferedInputStream bis = new BufferedInputStream(fos);
            int tag;
            System.out.println(base);
            //将源文件写入到zip文件中,若原本是zip文件,则压缩成压缩比率更高的7Z文件
            while ((tag = bis.read()) != -1) {
                out.write(tag);
            }
            fos.close();
            out.flush();
            bis.close();
        }
    }

    /**
     * @description:打包成Tar
     * @author Rorschach
     * @date 2019-05-23 15:52
     */
    public void tarCompress(TarArchiveOutputStream out, File sourceFile, String base) throws Exception {
        InputStream inputStream;
        //如果路径为目录(文件夹)
        if (sourceFile.isDirectory()) {
            //取出文件夹中的文件(或子文件夹)
            File[] flist = sourceFile.listFiles();
            if (flist.length == 0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
            {
                System.out.println(base + "/");
                out.putArchiveEntry(new TarArchiveEntry(base + "/"));
            } else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
            {
                for (int i = 0; i < flist.length; i++) {
                    tarCompress(out, flist[i], base + "/" + flist[i].getName());
                }
            }
        } else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
        {
            out.putArchiveEntry(new TarArchiveEntry(sourceFile, sourceFile.getName()));//打包的时候只是包含文件,不带路径
            inputStream = new FileInputStream(sourceFile);
            IOUtils.copy(inputStream, out);
            out.closeArchiveEntry();
        }
    }


    /**
     * @description: 把tar压缩成gz文件
     * @author Rorschach
     * @date 2019-05-23 15:52
     */
    public static boolean gzipCompression(String filePath, String resultFilePath) throws IOException {
        logger.info(" gzipCompression -> Compression start!");
        InputStream fin = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        GzipCompressorOutputStream gcos = null;
        try {
            fin = Files.newInputStream(Paths.get(filePath));
            bis = new BufferedInputStream(fin);
            fos = new FileOutputStream(resultFilePath);
            bos = new BufferedOutputStream(fos);
            gcos = new GzipCompressorOutputStream(bos);
            byte[] buffer = new byte[1024];
            int read = -1;
            while ((read = bis.read(buffer)) != -1) {
                gcos.write(buffer, 0, read);
            }
        } finally {
            new File(filePath).delete();
            if (gcos != null)
                gcos.close();
            if (bos != null)
                bos.close();
            if (fos != null)
                fos.close();
            if (bis != null)
                bis.close();
            if (fin != null)
                fin.close();
        }
        logger.info(" gzipCompression -> Compression end!");
        return true;
    }


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
ZipOutputStreamJava中一个用于压缩文件的类。它可以将多个文件或文件夹压缩成一个zip文件,并且可以设置压缩级别、密码等选项。 下面是一个简单的例子,展示如何使用ZipOutputStream将一个文件夹中的所有文件压缩成一个zip文件: ```java import java.io.*; import java.util.zip.*; public class ZipDirectory { public static void main(String[] args) throws IOException { String inputFolder = "/path/to/input/folder"; String outputZipFile = "/path/to/output/zipfile.zip"; // 创建输出流 FileOutputStream fos = new FileOutputStream(outputZipFile); ZipOutputStream zos = new ZipOutputStream(fos); // 遍历文件夹中的所有文件,并逐一添加到ZipOutputStream中 File folder = new File(inputFolder); for (File file : folder.listFiles()) { if (!file.isDirectory()) { addToZipFile(file, zos); } } // 关闭输出流 zos.close(); fos.close(); } private static void addToZipFile(File file, ZipOutputStream zos) throws IOException { FileInputStream fis = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } zos.closeEntry(); fis.close(); } } ``` 在上面的例子中,我们首先创建了一个ZipOutputStream,然后遍历指定的文件夹中的所有文件,并使用addToZipFile()方法将每个文件逐一添加到ZipOutputStream中。在addToZipFile()方法中,我们首先创建一个ZipEntry对象,指定要添加到zip文件中的文件名,然后读取文件的内容,并将其写入ZipOutputStream中。最后,我们关闭ZipEntry和FileInputStream。 需要注意的是,ZipOutputStream只能压缩文件,不能压缩文件夹本身。如果要压缩整个文件夹,必须遍历文件夹中的所有文件,并将它们逐一添加到ZipOutputStream中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rorschach01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值