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);
的来源。 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!");
}
}
在我的经验中ApacheCompress
比Plexus Archiver更为成熟,特别是因为Http://jira.codehaus.org/browse/browse/plxcomp-131,1.
如果您打算压缩/解压缩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;
truevfs
new TFile("archive.tar.gz").cp_rp(new File("dest/folder"));
但要提防依赖性问题。