7 ответов:
Примечание: эта функция была позже опубликована через отдельный проект, Apache Commons Compress, как описано в другом ответе. этот ответ устарел.
Я не использовал API tar напрямую, но tar и bzip2 реализованы в Ant; вы можете заимствовать их реализацию или, возможно, использовать Ant для выполнения того, что вам нужно.
Gzip является частью Java SE (и я предполагаю, что реализация Ant следует та же модель).
GZIPInputStreamэто простоInputStreamоформителя. Вы можете обернуть, например, aFileInputStreamнаGZIPInputStreamи использовать его так же, как вы бы использовать любойInputStream:InputStream is = new GZIPInputStream(new FileInputStream(file));(обратите внимание, что GZIPInputStream имеет свой собственный внутренний буфер, поэтому обертывание
FileInputStreamнаBufferedInputStreamвероятно, уменьшить производительность.)
вы можете сделать это с помощью библиотеки сжатия Apache Commons. Вы можете скачать версию 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; }
Apache Commons VFS поддерживает tar как виртуальная файловая система, который поддерживает URL-адреса, как этот
tar:gz:http://anyhost/dir/mytar.tar.gz!/mytar.tar!/path/in/tar/README.txtTrueZip или его правопреемником TrueVFS делает то же самое ... он также доступен из Maven Central.
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 Compress API имеет также поддержку tar, первоначально основанную на ICE Engineering Java Tar Package, который является как API, так и автономным инструментом.
Как насчет использования этого API для tar файлов, это другой включены внутри муравья для BZIP2 и стандартный для GZIP?
Comments