如何在java中压缩/解压tar.gz文件

发布于 2024-11-30 21:37:15 字数 69 浏览 1 评论 0 原文

谁能告诉我在java中压缩和解压缩tar.gzip文件的正确方法我一直在搜索,但我能找到的最多的是zip或gzip(单独)。

Can anyone show me the correct way to compress and decompress tar.gzip files in java i've been searching but the most i can find is either zip or gzip(alone).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

独自唱情﹋歌 2024-12-07 21:37:16

为了提取 .tar.gz 格式的内容,我成功地使用了 apache commons-compress ('org.apache.commons:commons-compress:1.12')。看一下这个示例方法:

public void extractTarGZ(InputStream in) {
    GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in);
    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) {
        TarArchiveEntry entry;

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
            /** If the entry is a directory, create the directory. **/
            if (entry.isDirectory()) {
                File f = new File(entry.getName());
                boolean created = f.mkdir();
                if (!created) {
                    System.out.printf("Unable to create directory '%s', during extraction of archive contents.\n",
                            f.getAbsolutePath());
                }
            } else {
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                FileOutputStream fos = new FileOutputStream(entry.getName(), false);
                try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
                    while ((count = tarIn.read(data, 0, BUFFER_SIZE)) != -1) {
                        dest.write(data, 0, count);
                    }
                }
            }
        }

        System.out.println("Untar completed successfully!");
    }
}

To extract the contents of .tar.gz format, I successfully use apache commons-compress ('org.apache.commons:commons-compress:1.12'). Take a look at this example method:

public void extractTarGZ(InputStream in) {
    GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in);
    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) {
        TarArchiveEntry entry;

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
            /** If the entry is a directory, create the directory. **/
            if (entry.isDirectory()) {
                File f = new File(entry.getName());
                boolean created = f.mkdir();
                if (!created) {
                    System.out.printf("Unable to create directory '%s', during extraction of archive contents.\n",
                            f.getAbsolutePath());
                }
            } else {
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                FileOutputStream fos = new FileOutputStream(entry.getName(), false);
                try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
                    while ((count = tarIn.read(data, 0, BUFFER_SIZE)) != -1) {
                        dest.write(data, 0, count);
                    }
                }
            }
        }

        System.out.println("Untar completed successfully!");
    }
}
橘亓 2024-12-07 21:37:16

根据我的经验,Apache CompressPlexus Archiver,特别是因为 http://jira.codehaus.org/browse/PLXCOMP-131

我相信 Apache Compress 也有更多的活动。

In my experience Apache Compress is much more mature than Plexus Archiver, specifically because of issues like http://jira.codehaus.org/browse/PLXCOMP-131.

I believe Apache Compress has more activity as well.

带上头具痛哭 2024-12-07 21:37:16

如果您计划在 Linux 上压缩/解压缩,您可以调用 shell 命令行来为您执行此操作:

Files.createDirectories(Paths.get(target));
ProcessBuilder builder = new ProcessBuilder();
builder.command("sh", "-c", String.format("tar xfz %s -C %s", tarGzPathLocation, target));
builder.directory(new File("/tmp"));
Process process = builder.start();
int exitCode = process.waitFor();
assert exitCode == 0;

If you are planning to compress/decompress on Linux, you can call the shell command line to do that for you:

Files.createDirectories(Paths.get(target));
ProcessBuilder builder = new ProcessBuilder();
builder.command("sh", "-c", String.format("tar xfz %s -C %s", tarGzPathLocation, target));
builder.directory(new File("/tmp"));
Process process = builder.start();
int exitCode = process.waitFor();
assert exitCode == 0;
箜明 2024-12-07 21:37:16

使用 TrueVFS 提取 Tar.GZip 存档很简单:

new TFile("archive.tar.gz").cp_rp(new File("dest/folder"));

但要注意 依赖关系问题

With TrueVFS extracting Tar.GZip archive is one-liner:

new TFile("archive.tar.gz").cp_rp(new File("dest/folder"));

But beware of dependencies issue.

缱绻入梦 2024-12-07 21:37:15

我为 commons-compress 编写了一个名为 jarchivelib 可以轻松地从 File 对象中提取或压缩。

示例代码如下所示:

File archive = new File("/home/thrau/archive.tar.gz");
File destination = new File("/home/thrau/archive/");

Archiver archiver = ArchiverFactory.createArchiver("tar", "gz");
archiver.extract(archive, destination);

I've written a wrapper for commons-compress called jarchivelib that makes it easy to extract or compress from and into File objects.

Example code would look like this:

File archive = new File("/home/thrau/archive.tar.gz");
File destination = new File("/home/thrau/archive/");

Archiver archiver = ArchiverFactory.createArchiver("tar", "gz");
archiver.extract(archive, destination);
哥,最终变帅啦 2024-12-07 21:37:15

我最喜欢的是 plexus-archiver - 请参阅 GitHub 上的源代码。

另一个选择是 Apache commons-compress - (请参阅 mvnrepository)。

使用 plexus-utils,取消归档的代码如下所示:

final TarGZipUnArchiver ua = new TarGZipUnArchiver();
// Logging - as @Akom noted, logging is mandatory in newer versions, so you can use a code like this to configure it:
ConsoleLoggerManager manager = new ConsoleLoggerManager();
manager.initialize();
ua.enableLogging(manager.getLoggerForComponent("bla"));
// -- end of logging part
ua.setSourceFile(sourceFile);
destDir.mkdirs();
ua.setDestDirectory(destDir);
ua.extract();

类似的 *Archiver 类也用于归档。

通过 Maven,您可以使用此依赖项

<dependency>
  <groupId>org.codehaus.plexus</groupId>
  <artifactId>plexus-archiver</artifactId>
  <version>2.2</version>
</dependency>

My favorite is plexus-archiver - see sources on GitHub.

Another option is Apache commons-compress - (see mvnrepository).

With plexus-utils, the code for unarchiving looks like this:

final TarGZipUnArchiver ua = new TarGZipUnArchiver();
// Logging - as @Akom noted, logging is mandatory in newer versions, so you can use a code like this to configure it:
ConsoleLoggerManager manager = new ConsoleLoggerManager();
manager.initialize();
ua.enableLogging(manager.getLoggerForComponent("bla"));
// -- end of logging part
ua.setSourceFile(sourceFile);
destDir.mkdirs();
ua.setDestDirectory(destDir);
ua.extract();

Similar *Archiver classes are there for archiving.

With Maven, you can use this dependency:

<dependency>
  <groupId>org.codehaus.plexus</groupId>
  <artifactId>plexus-archiver</artifactId>
  <version>2.2</version>
</dependency>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文