java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java打成压缩包

Java打成各种压缩包的方法详细汇总

作者:程序员阿诚

在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载,下面这篇文章主要给大家介绍了关于Java打成各种压缩包的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

1.将指定目录下的文件打包成 .zip

代码示例:

import java.io.*;
import java.util.zip.*;

public class ZipFiles {
    public static void main(String[] args) {
        // 要压缩的文件或文件夹
        String sourceFile = "path/to/your/source/file_or_folder";

        // 压缩后的ZIP文件名
        String zipFileName = "output.zip";

        // 创建一个输出流将数据写入ZIP文件
        try (FileOutputStream fos = new FileOutputStream(zipFileName);
             ZipOutputStream zos = new ZipOutputStream(fos)) {

            // 调用递归方法压缩文件或文件夹
            addToZipFile(sourceFile, sourceFile, zos);

            System.out.println("文件已成功打包成 " + zipFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addToZipFile(String path, String sourceFile, ZipOutputStream zos) throws IOException {
        File file = new File(sourceFile);

        // 如果是文件夹,则获取其内容并递归调用此方法
        if (file.isDirectory()) {
            String[] fileList = file.list();
            if (fileList != null) {
                for (String fileName : fileList) {
                    addToZipFile(path, sourceFile + File.separator + fileName, zos);
                }
            }
            return;
        }

        // 如果是文件,则将其添加到ZIP文件中
        try (FileInputStream fis = new FileInputStream(sourceFile)) {
            String entryName = sourceFile.substring(path.length() + 1); // 获取ZIP中的条目名称
            ZipEntry zipEntry = new ZipEntry(entryName);
            zos.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }
        }
    }
}

将 path/to/your/source/file_or_folder 替换为要打包的文件或文件夹的路径,然后运行该代码。它将创建一个名为 output.zip 的ZIP文件,其中包含指定路径下的文件或文件夹。

2.将指定目录下的文件打包成 .tar.gz

可以使用 Java 中的 java.util.zip 包来创建 .tar.gz 文件。尽管 Java 的标准库没有直接提供对 .tar 格式的支持,但你可以使用 TarArchiveOutputStream 以及 GzipCompressorOutputStream 来创建 tar.gz 归档文件。以下是一个示例:

import org.apache.commons.compress.archivers.tar.*;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;

import java.io.*;

public class TarGzFiles {
    public static void main(String[] args) {
        // 要压缩的文件或文件夹
        String sourceFile = "path/to/your/source/file_or_folder";

        // 压缩后的tar.gz文件名
        String tarGzFileName = "output.tar.gz";

        try {
            FileOutputStream fos = new FileOutputStream(tarGzFileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            GzipCompressorOutputStream gzos = new GzipCompressorOutputStream(bos);
            TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(gzos);

            File file = new File(sourceFile);
            addToTarArchive(file, tarArchive);

            tarArchive.finish();
            tarArchive.close();

            System.out.println("文件已成功打包成 " + tarGzFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addToTarArchive(File file, TarArchiveOutputStream tarArchive) throws IOException {
        String entryName = file.getName();
        TarArchiveEntry tarEntry = new TarArchiveEntry(file, entryName);

        tarArchive.putArchiveEntry(tarEntry);

        if (file.isFile()) {
            try (FileInputStream fis = new FileInputStream(file)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    tarArchive.write(buffer, 0, len);
                }
                tarArchive.closeArchiveEntry();
            }
        } else if (file.isDirectory()) {
            tarArchive.closeArchiveEntry();
            File[] children = file.listFiles();
            if (children != null) {
                for (File child : children) {
                    addToTarArchive(child, tarArchive);
                }
            }
        }
    }
}

在此示例中,使用了 Apache Commons Compress 库,你可以在 Maven =添加以下依赖:

Maven:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.21</version> <!-- 或者更高的版本 -->
</dependency>

确保将 path/to/your/source/file_or_folder 替换为要打包的文件或文件夹的实际路径,然后运行代码以创建 output.tar.gz 文件。

3.将指定目录下的文件打包成 .tar

Java的标准库中并没有直接支持创建.tar格式文件的类,但你可以使用Apache Commons Compress库来完成这个任务。下面是一个示例代码:

首先,确保你在项目中包含了Apache Commons Compress库。如果使用Maven,可以在pom.xml文件中添加以下依赖项:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.21</version> <!-- 或者更高的版本 -->
</dependency>

然后,使用以下代码将文件打包成.tar文件:

import org.apache.commons.compress.archivers.tar.*;
import org.apache.commons.compress.utils.IOUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class TarFiles {
    public static void main(String[] args) {
        // 要打包的文件或文件夹
        String sourceFile = "path/to/your/source/file_or_folder";

        // 打包后的tar文件名
        String tarFileName = "output.tar";

        try {
            FileOutputStream fos = new FileOutputStream(tarFileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(bos);

            addToTarArchive(sourceFile, tarArchive);

            tarArchive.finish();
            tarArchive.close();

            System.out.println("文件已成功打包成 " + tarFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addToTarArchive(String filePath, TarArchiveOutputStream tarArchive) throws IOException {
        Path sourcePath = Paths.get(filePath);
        String baseDir = sourcePath.getFileName().toString();

        Files.walk(sourcePath)
                .filter(path -> !Files.isDirectory(path))
                .forEach(path -> {
                    try {
                        String entryName = baseDir + File.separator + sourcePath.relativize(path).toString();
                        TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), entryName);
                        tarArchive.putArchiveEntry(tarEntry);

                        FileInputStream fis = new FileInputStream(path.toFile());
                        IOUtils.copy(fis, tarArchive);
                        fis.close();

                        tarArchive.closeArchiveEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    }
}

在这个示例中,我们使用了Apache Commons Compress库来创建.tar文件。确保将path/to/your/source/file_or_folder替换为你要打包的实际文件或文件夹的路径,并运行代码来创建output.tar文件。

4.将指定目录下的文件打包成 .rar

在Java中,压缩成RAR格式的操作稍微有些复杂,因为RAR格式是一种专有格式,并没有Java标准库提供直接支持。为了压缩文件为RAR格式,你可以使用第三方库,比如通过调用WinRAR或其他命令行工具来实现。

一种方法是使用Java的ProcessBuilder来运行命令行来执行WinRAR或其他RAR压缩工具的命令。以下是一个简单的示例,假设你已经安装了WinRAR并将其路径添加到了系统的环境变量中:

import java.io.*;

public class RARFiles {
    public static void main(String[] args) {
        // 要压缩的文件或文件夹
        String sourceFile = "path/to/your/source/file_or_folder";

        // 压缩后的RAR文件名
        String rarFileName = "output.rar";

        try {
            // 构建命令行
            String[] command = {"cmd", "/c", "rar", "a", "-r", rarFileName, sourceFile};

            // 创建进程并执行命令
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();

            // 读取进程输出(可选)
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待进程执行结束
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("文件已成功打包成 " + rarFileName);
            } else {
                System.out.println("打包过程中出现错误");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

请替换 path/to/your/source/file_or_folder 为你要压缩的文件或文件夹的路径,并确保系统中已经正确安装和配置了WinRAR。

记住,这种方法需要系统中安装有WinRAR并且路径被正确添加到系统的环境变量中,且这个示例中的代码并没有对WinRAR命令返回的错误进行详细处理。

5.生成若干个txt并打包到zip中

代码示例:

import java.io.*;
import java.util.zip.*;

public class GenerateTxtFilesAndZip {
    public static void main(String[] args) {
        String basePath = "path/to/your/directory"; // 更换为你想要保存文件的文件夹路径
        int fileCount = 10; // 要生成的文件数量

        try {
            // 创建文件夹(如果不存在)
            File directory = new File(basePath);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 生成txt文件并写入内容
            for (int i = 1; i <= fileCount; i++) {
                String fileName = "file" + i + ".txt";
                String filePath = basePath + File.separator + fileName;
                String fileContent = "This is the content of " + fileName;

                try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
                    writer.write(fileContent);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 打包成zip文件
            String zipFileName = "output.zip";
            byte[] buffer = new byte[1024];

            FileOutputStream fos = new FileOutputStream(zipFileName);
            ZipOutputStream zos = new ZipOutputStream(fos);

            File dir = new File(basePath);
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.getName().endsWith(".txt")) {
                        FileInputStream fis = new FileInputStream(file);
                        zos.putNextEntry(new ZipEntry(file.getName()));

                        int length;
                        while ((length = fis.read(buffer)) > 0) {
                            zos.write(buffer, 0, length);
                        }

                        zos.closeEntry();
                        fis.close();
                    }
                }
            }

            zos.close();
            System.out.println("文件已成功打包成 " + zipFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请替换path/to/your/directory为你想要保存生成文件的实际文件夹路径。这段代码会在指定路径下生成10个.txt文件,并将它们打包成一个名为output.zip的ZIP文件。

附:Java实现zip、tar、tar.gz 打包压缩解压

package com.bj.drj;

import cn.hutool.core.lang.Console;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.io.IOUtils;

import java.io.*;

/**
 * @ClassName PackAndCompressionUtils
 * @Description: 解压压缩文件
 * @Author drj
 * @Date 2021/9/18
 * @Version V1.0
 **/
public class PackAndCompressionUtils {


    private PackAndCompressionUtils() {
    }

    /**
     * 这个方法主要针对文件实现打包tar 也可以生成tar.gz 但是失去了gz 压缩功能 只是现实了打包。
     *
     * @param filesPathArray 需要打包的文件
     * @param targetDirPath  生成tar 目录
     * @return
     * @throws Exception
     */
    public static boolean tarPack(String[] filesPathArray, String targetDirPath) throws Exception {
        try (FileOutputStream fileOutputStream = new FileOutputStream(new File(targetDirPath));
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
             TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(bufferedOutputStream)) {
            for (String filePath : filesPathArray) {
                try (FileInputStream fileInputStream = new FileInputStream(new File(filePath))) {
                    File file = new File(filePath);
                    TarArchiveEntry tae = new TarArchiveEntry(file, file.getName());
                    tarArchiveOutputStream.putArchiveEntry(tae);
                    IOUtils.copy(fileInputStream, tarArchiveOutputStream);
                    tarArchiveOutputStream.closeArchiveEntry();
                } catch (Exception e) {
                    Console.error(e, "异常信息:{}", filePath);
                }
            }
        } catch (Exception e) {
            Console.error(e, "异常信息:{}", filesPathArray);
        }
        return true;
    }

    /**
     * 解压打包文件
     *
     * @param unPackFilePath
     * @param targetDirPath
     * @return
     * @throws Exception
     */
    public static boolean tarUnpack(String unPackFilePath, String targetDirPath) throws Exception {
        try (FileInputStream fileInputStream = new FileInputStream(new File(unPackFilePath));
             TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(fileInputStream)) {
            TarArchiveEntry tae = null;
            while ((tae = tarArchiveInputStream.getNextTarEntry()) != null) {
                String dir = targetDirPath + File.separator + tae.getName();
                try (FileOutputStream fileOutputStream = new FileOutputStream(new File(dir));
                     BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)) {
                    IOUtils.copy(tarArchiveInputStream, bufferedOutputStream);
                } catch (Exception ex) {
                    Console.error(ex, "异常文件:{}", dir);
                }
            }
        } catch (Exception ex) {
            Console.error(ex, "异常文件:{}", unPackFilePath);
        }
        return true;
    }

    /**
     * gzip压缩文件 后缀是.gz
     *
     * @param filesPathArray
     * @param targetDirPath
     * @return
     * @throws IOException
     */
    public static boolean gzipCompress(String[] filesPathArray, String targetDirPath) throws IOException {
        try (OutputStream outputStream = new FileOutputStream(new File(targetDirPath));
             GzipCompressorOutputStream gzipCompressorOutputStream = new GzipCompressorOutputStream(outputStream)) {
            for (String filePath : filesPathArray) {
                try (InputStream inputStream = new FileInputStream(new File(filePath));) {
                    TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(gzipCompressorOutputStream);
                    File file = new File(filePath);
                    TarArchiveEntry archiveEntry = new TarArchiveEntry(file, file.getName());
                    tarArchiveOutputStream.putArchiveEntry(archiveEntry);
                    IOUtils.copy(inputStream, tarArchiveOutputStream);
                    tarArchiveOutputStream.closeArchiveEntry();
                } catch (Exception ex) {
                    Console.error(ex, "异常文件:{}", filePath);
                }
            }

        } catch (Exception ex) {
            Console.error(ex, "异常文件:{}", filesPathArray);
        }

        return true;
    }


    /**
     * 针对gz包 进行解压
     *
     * @param sourceDir
     * @param targetDirPath
     */
    public static boolean gzipDeCompress(String sourceDir, String targetDirPath) {
        try (
                FileInputStream fileInputStream = new FileInputStream(sourceDir);
                GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream);
                TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(gzipCompressorInputStream);
        ) {
            TarArchiveEntry tarArchiveEntry = null;
            while ((tarArchiveEntry = tarArchiveInputStream.getNextTarEntry()) != null) {
                String dir = targetDirPath + File.separator + tarArchiveEntry.getName();
                try (FileOutputStream fileOutputStream = new FileOutputStream(new File(dir))) {
                    IOUtils.copy(tarArchiveInputStream, fileOutputStream);
                } catch (Exception ex) {
                    Console.error(ex, "异常文件路径:{}", sourceDir);
                }
            }

        } catch (Exception ex) {
            Console.error(ex, "异常文件路径:{}", sourceDir);
        }
        return true;
    }


    /**
     * 对文件进行zip打包处理
     *
     * @param filesPathArray
     * @param targetDirPath
     * @return
     * @throws Exception
     */
    public static boolean zipCompress(String[] filesPathArray, String targetDirPath) throws Exception {
        try (FileOutputStream fileOutputStream = new FileOutputStream(new File(targetDirPath));
             ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(fileOutputStream)) {

            for (String filePath : filesPathArray) {
                try (FileInputStream fileInputStream = new FileInputStream(new File(filePath))) {
                    File file = new File(filePath);
                    ZipArchiveEntry zae = new ZipArchiveEntry(file, file.getName());
                    zipArchiveOutputStream.putArchiveEntry(zae);
                    IOUtils.copy(fileInputStream, zipArchiveOutputStream);
                    zipArchiveOutputStream.closeArchiveEntry();
                } catch (Exception ex) {
                    Console.error(ex, "异常文件路径:{}", filePath);
                }

            }
        } catch (Exception ex) {
            Console.error(ex, "异常文件路径:{}", filesPathArray);
        }
        return true;
    }


    /**
     * 解压zip 文件
     *
     * @param decompressFilePath
     * @param targetDirPath
     * @return
     * @throws Exception
     */
    public static boolean zipDecompress(String decompressFilePath, String targetDirPath) throws Exception {

        try (FileInputStream fileInputStream = new FileInputStream(new File(decompressFilePath));
             ZipArchiveInputStream zipArchiveInputStream = new ZipArchiveInputStream(fileInputStream)) {
            ZipArchiveEntry zae = null;
            while ((zae = zipArchiveInputStream.getNextZipEntry()) != null) {
                String dir = targetDirPath + File.separator + zae.getName();
                try (FileOutputStream fileOutputStream = new FileOutputStream(new File(dir))) {
                    IOUtils.copy(zipArchiveInputStream, fileOutputStream);
                } catch (Exception ex) {
                    Console.error(ex, "异常文件路径:{}", dir);
                }
            }
        } catch (Exception ex) {
            Console.error(ex, "异常文件路径:{}", decompressFilePath);
        }
        return true;
    }
}

单元测试

    String[] filesPathArray = new String[]{"D:\\core\\a.txt", "D:\\core\\b.txt"};
    String[] fileTarPath = new String[]{"D:\\core\\tarcompress.tar"};
    String compressTarTargetDirPath = "D:\\core\\tarcompress.tar.gz";
    String compressZipTargetDirPath = "D:\\core\\tarcompress.zip";
    String compressGzTargetDirPath = "D:\\core\\tarcompress3.gz";
    String compressGzTargetDirPath4 = "D:\\core\\tarcompress4.gz";
    String deCompressDirPath = "D:\\core";

    @Test
    public void testTarPack() throws Exception {
        boolean b = PackAndCompressionUtils.tarPack(filesPathArray, compressTarTargetDirPath);
        Assert.assertTrue(b);
    }

    @Test
    public void testTarUnpack() throws Exception {
        boolean b = PackAndCompressionUtils.tarUnpack(compressGzTargetDirPath, deCompressDirPath);
        Assert.assertTrue(b);
    }

    @Test
    public void testZipCompress() throws Exception {
        boolean b = PackAndCompressionUtils.zipCompress(filesPathArray, compressZipTargetDirPath);
        Assert.assertTrue(b);
    }

    @Test
    public void testZipDeCompress() throws Exception {
        boolean b = PackAndCompressionUtils.zipDecompress(compressZipTargetDirPath, deCompressDirPath);
        Assert.assertTrue(b);
    }

    @Test
    public void test() throws Exception {
        MyUnTarGzUtil.unTarGz(compressGzTargetDirPath,deCompressDirPath);
    }


    @Test
    public void testGzCompress() throws Exception {
        boolean b = PackAndCompressionUtils.gzipCompress(filesPathArray, compressGzTargetDirPath4);
        Assert.assertTrue(b);
    }

    @Test
    public void testGzDeCompress() throws Exception {
        boolean b = PackAndCompressionUtils.gzipDeCompress(compressTarTargetDirPath, deCompressDirPath);
        Assert.assertTrue(b);
    }

总结

到此这篇关于Java打成各种压缩包的文章就介绍到这了,更多相关Java打成压缩包内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文