문제
Java에서 Tar (또는 Tar.gz 또는 Tar.bz2) 파일을 어떻게 추출합니까?
해결책
메모: 이 기능은 나중에 별도의 프로젝트 인 Apache Commons Compress를 통해 게시되었습니다. 다른 대답에 설명되어 있습니다. 이 답변은 구식입니다.
나는 TAR API를 직접 사용하지 않았지만 TAR 및 BZIP2는 ANT에서 구현됩니다. 구현을 빌리거나 Ant를 사용하여 필요한 작업을 수행 할 수 있습니다.
GZIP는 Java SE의 일부입니다 (ANT 구현이 동일한 모델을 따르는 것 같아요).
GZIPInputStream
그냥 an입니다 InputStream
데코레이터. 예를 들어 a FileInputStream
안에 GZIPInputStream
그리고 당신이 사용하는 것과 같은 방식으로 그것을 사용하십시오. InputStream
:
InputStream is = new GZIPInputStream(new FileInputStream(file));
(gzipinputstream에는 자체 내부 버퍼가 있으므로 FileInputStream
안에 BufferedInputStream
아마도 성능을 줄일 것입니다.)
다른 팁
Apache Commons Compress 라이브러리로이를 수행 할 수 있습니다. 1.2 버전을 다운로드 할 수 있습니다 http://mvnrepository.com/artifact/org.apache.commons/commons-compress/1.2.
두 가지 방법은 다음과 같습니다. 하나는 파일을 압축하고 다른 하나는 그것을 방해하는 것입니다. 따라서 파일의 경우u003CfileName> 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;
}
아파치 커먼즈 VFS 타르를 a로지지합니다 가상 파일 시스템, 이와 같은 URL을 지원합니다 tar:gz:http : //anyhost/dir/mytar.tar.gz! /mytar.tar! /path/in/tar/readme.txt
Archiver archiver = ArchiverFactory.createArchiver("tar", "gz");
archiver.extract(archiveFile, destDir);
의존:
<dependency>
<groupId>org.rauschig</groupId>
<artifactId>jarchivelib</artifactId>
<version>0.5.0</version>
</dependency>
방금 제안 된 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>
GZIP 및 BZIP2 외에도 Apache Commons는 API를 압축합니다 원래 기반으로 TAR 지원이 있습니다 아이스 엔지니어링 자바 타르 패키지, API 및 독립형 도구입니다.
다음은 다음과 같은 버전입니다 이 이전 답변 Dan Borza에 의해 사용됩니다 Apache Commons는 압축합니다 및 Java Nio (즉, 파일 대신 경로). 또한 하나의 스트림에서 무수압과 비 타격을 수행하므로 중간 파일 생성이 없습니다.
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();
}