Как извлечь файл tar (или tar.gz или tar.bz2) в Java?
Как извлечь tar файл в Java?
Ответ 1
Примечание. Эта функция была позже опубликована через отдельный проект, Apache Commons Compress, как описанный в другом ответе. Этот ответ устарел.
Я не использовал tar API напрямую, но tar и bzip2 реализованы в Ant; вы могли бы заимствовать их реализацию или, возможно, использовать Ant, чтобы делать то, что вам нужно.
Gzip является частью Java SE (и я предполагаю, что реализация Ant следует той же модели).
GZIPInputStream
- это просто декоратор InputStream
. Вы можете обернуть, например, FileInputStream
в GZIPInputStream
и использовать его так же, как вы бы использовали любой InputStream
:
InputStream is = new GZIPInputStream(new FileInputStream(file));
(Обратите внимание, что GZIPInputStream имеет свой собственный внутренний буфер, поэтому обертка FileInputStream
в BufferedInputStream
, вероятно, снизит производительность.)
Ответ 2
Вы можете сделать это с помощью библиотеки Apache Commons Compress. Вы можете загрузить версию 1.2 из http://mvnrepository.com/artifact/org.apache.commons/commons-compress/1.2.
Вот два метода: один, который распаковывает файл, а другой - его. Итак, для файла <имя_файла> 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;
}
Ответ 3
Apache Commons VFS поддерживает tar как виртуальную файловую систему, которая поддерживает такие URL-адреса, как этот tar:gz:http://anyhost/dir/mytar.tar.gz!/mytar.tar!/path/in/tar/README.txt
TrueZip или его преемник TrueVFS делает то же самое... он также доступен от Maven Central.
Ответ 4
Archiver archiver = ArchiverFactory.createArchiver("tar", "gz");
archiver.extract(archiveFile, destDir);
Зависимость:
<dependency>
<groupId>org.rauschig</groupId>
<artifactId>jarchivelib</artifactId>
<version>0.5.0</version>
</dependency>
Ответ 5
Я просто попробовал кучу предлагаемых 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>
Ответ 6
В дополнение к gzip и bzip2 Apache Commons Compress API также поддерживает tar, основываясь на ICE Engineering Java Tar Package, который является как API, так и автономным инструментом.
Ответ 7
Как насчет использования этого API для файлов tar, это другое один включен внутри Ant для BZIP2 и стандартный для для GZIP?