kdg*_*ill 38 java compression gzip tar
任何人都可以告诉我压缩和解压缩java中的tar.gzip文件的正确方法我一直在搜索,但我能找到的最多是zip或gzip(单独).
thr*_*rau 34
我为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);
Run Code Online (Sandbox Code Playgroud)
Pet*_*lka 28
我最喜欢的是plexus-archiver - 请参阅GitHub上的消息来源.
另一种选择是Apache commons-compress - (参见mvnrepository).
使用plexus-utils,unarchiving的代码如下所示:
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();
Run Code Online (Sandbox Code Playgroud)
类似的*Archiver类可用于存档.
使用Maven,您可以使用此依赖项:
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-archiver</artifactId>
<version>2.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
Rem*_*usS 13
要提取.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!");
}
}
Run Code Online (Sandbox Code Playgroud)
根据我的经验,Apache Compress比Plexus Archiver更加成熟,特别是因为像http://jira.codehaus.org/browse/PLXCOMP-131这样的问题.
我相信Apache Compress也有更多的活动.
| 归档时间: |
|
| 查看次数: |
69351 次 |
| 最近记录: |