如何在Java

问题描述 投票:0回答:5
任何人都可以向我展示我一直在搜索的Java中压缩和解压缩tar.gzip文件的正确方法,但我最多能找到的是zip或gzip(单独)。

java gzip tar compression
5个回答
44
投票
我为

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);



33
投票
Github

的来源。 Athother选项是Apachecommons -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();

仿真 *档案堂都在那里归档。

与Maven,您可以使用此

依赖关系

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

要提取.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!");
    }
}

19
投票

在我的经验中ApacheCompress

比Plexus Archiver
更为成熟,特别是因为
Http://jira.codehaus.org/browse/browse/plxcomp-131,1.


1
投票

new TFile("archive.tar.gz").cp_rp(new File("dest/folder")); 但要提防依赖性问题。


最新问题
© www.soinside.com 2019 - 2024. All rights reserved.