如何在Java中提取tar(或tar.gz或tar.bz2)文件?
答案 0 :(得分:67)
您可以使用Apache Commons Compress库执行此操作。您可以从http://mvnrepository.com/artifact/org.apache.commons/commons-compress/1.2下载1.2版本。
以下是两种方法:一种解压缩文件,另一种解压缩文件。所以,对于一个文件 < fileName> tar.gz,你需要首先解压缩它然后解压缩它。请注意,tar存档也可能包含文件夹,需要在本地文件系统上创建它们。
享受。
/** Untar an input file into an output file.
* The output file is created in the output folder, having the same name
* as the input file, minus the '.tar' extension.
*
* @param inputFile the input .tar file
* @param outputDir the output directory file.
* @throws IOException
* @throws FileNotFoundException
*
* @return The {@link List} of {@link File}s with the untared content.
* @throws ArchiveException
*/
private static List<File> unTar(final File inputFile, final File outputDir) throws FileNotFoundException, IOException, ArchiveException {
LOG.info(String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));
final List<File> untaredFiles = new LinkedList<File>();
final InputStream is = new FileInputStream(inputFile);
final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
TarArchiveEntry entry = null;
while ((entry = (TarArchiveEntry)debInputStream.getNextEntry()) != null) {
final File outputFile = new File(outputDir, entry.getName());
if (entry.isDirectory()) {
LOG.info(String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath()));
if (!outputFile.exists()) {
LOG.info(String.format("Attempting to create output directory %s.", outputFile.getAbsolutePath()));
if (!outputFile.mkdirs()) {
throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
}
}
} else {
LOG.info(String.format("Creating output file %s.", outputFile.getAbsolutePath()));
final OutputStream outputFileStream = new FileOutputStream(outputFile);
IOUtils.copy(debInputStream, outputFileStream);
outputFileStream.close();
}
untaredFiles.add(outputFile);
}
debInputStream.close();
return untaredFiles;
}
/**
* Ungzip an input file into an output file.
* <p>
* The output file is created in the output folder, having the same name
* as the input file, minus the '.gz' extension.
*
* @param inputFile the input .gz file
* @param outputDir the output directory file.
* @throws IOException
* @throws FileNotFoundException
*
* @return The {@File} with the ungzipped content.
*/
private static File unGzip(final File inputFile, final File outputDir) throws FileNotFoundException, IOException {
LOG.info(String.format("Ungzipping %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));
final File outputFile = new File(outputDir, inputFile.getName().substring(0, inputFile.getName().length() - 3));
final GZIPInputStream in = new GZIPInputStream(new FileInputStream(inputFile));
final FileOutputStream out = new FileOutputStream(outputFile);
IOUtils.copy(in, out);
in.close();
out.close();
return outputFile;
}
答案 1 :(得分:18)
注意:此功能后来通过单独的项目Apache Commons Compress发布,described in another answer.此答案已过期。
我没有直接使用tar API,但是tar和bzip2是在Ant中实现的;你可以借用他们的实现,或者可能使用Ant来做你需要的。
Gzip is part of Java SE(我猜测Ant实现遵循相同的模型)。
GZIPInputStream
只是一个InputStream
装饰者。例如,您可以在FileInputStream
中换行GZIPInputStream
并以与使用任何InputStream
相同的方式使用它:
InputStream is = new GZIPInputStream(new FileInputStream(file));
(请注意,GZIPInputStream有自己的内部缓冲区,因此将FileInputStream
包裹在BufferedInputStream
中可能会降低性能。)
答案 2 :(得分:12)
Apache Commons VFS支持tar作为虚拟文件系统,它支持此类网址tar:gz:http://anyhost/dir/mytar.tar.gz!/mytar.tar!/path/in/tar/README.txt
答案 3 :(得分:10)
Archiver archiver = ArchiverFactory.createArchiver("tar", "gz");
archiver.extract(archiveFile, destDir);
相关性:
<dependency>
<groupId>org.rauschig</groupId>
<artifactId>jarchivelib</artifactId>
<version>0.5.0</version>
</dependency>
答案 4 :(得分:7)
我刚刚尝试了一堆建议的libs(TrueZip,Apache Compress),但没有运气。
这是Apache Commons VFS的一个例子:
FileSystemManager fsManager = VFS.getManager();
FileObject archive = fsManager.resolveFile("tgz:file://" + fileName);
// List the children of the archive file
FileObject[] children = archive.getChildren();
System.out.println("Children of " + archive.getName().getURI()+" are ");
for (int i = 0; i < children.length; i++) {
FileObject fo = children[i];
System.out.println(fo.getName().getBaseName());
if (fo.isReadable() && fo.getType() == FileType.FILE
&& fo.getName().getExtension().equals("nxml")) {
FileContent fc = fo.getContent();
InputStream is = fc.getInputStream();
}
}
maven依赖:
<dependency>
<groupId>commons-vfs</groupId>
<artifactId>commons-vfs</artifactId>
<version>1.0</version>
</dependency>
答案 5 :(得分:5)
除了gzip和bzip2之外,Apache Commons Compress API还支持tar,最初基于ICE Engineering Java Tar Package,它既是API又是独立工具。
答案 6 :(得分:4)
如果将此API用于tar文件,那么这个other one包含在BZIP2的Ant中,而standard one包含在GZIP中?
答案 7 :(得分:0)
这是Dan Borza基于this earlier answer的版本,它使用Apache Commons Compress和Java NIO(即,路径而不是File)。它还可以在一个流中执行解压缩和解压缩,因此不会创建中间文件。
public static void unTarGz( Path pathInput, Path pathOutput ) throws IOException {
TarArchiveInputStream tararchiveinputstream =
new TarArchiveInputStream(
new GzipCompressorInputStream(
new BufferedInputStream( Files.newInputStream( pathInput ) ) ) );
ArchiveEntry archiveentry = null;
while( (archiveentry = tararchiveinputstream.getNextEntry()) != null ) {
Path pathEntryOutput = pathOutput.resolve( archiveentry.getName() );
if( archiveentry.isDirectory() ) {
if( !Files.exists( pathEntryOutput ) )
Files.createDirectory( pathEntryOutput );
}
else
Files.copy( tararchiveinputstream, pathEntryOutput );
}
tararchiveinputstream.close();
}