当前位置: 代码网 > it编程>编程语言>Java > Java打成各种压缩包的方法详细汇总

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

2024年06月17日 Java 我要评论
1.将指定目录下的文件打包成 .zip代码示例:import java.io.*;import java.util.zip.*;public class zipfiles { public st

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打成压缩包内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com