List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveEntry getName
public String getName()
From source file:de.uzk.hki.da.pkg.NativeJavaTarArchiveBuilder.java
public void unarchiveFolder(File srcTar, File destFolder) throws Exception { FileInputStream fin = new FileInputStream(srcTar); BufferedInputStream in = new BufferedInputStream(fin); TarArchiveInputStream tIn = new TarArchiveInputStream(in); HashMap<String, Long> modDateMap = new HashMap<String, Long>(); TarArchiveEntry entry; do {//from ww w. j av a 2 s.com entry = tIn.getNextTarEntry(); if (entry == null) break; logger.debug(entry.getName()); String dstName = destFolder.getAbsolutePath() + "/" + entry.getName(); File entryFile = new File(dstName); if (entry.isDirectory()) { entryFile.mkdirs(); modDateMap.put(dstName, new Long(entry.getModTime().getTime())); } else { new File(entryFile.getAbsolutePath().substring(0, entryFile.getAbsolutePath().lastIndexOf('/'))) .mkdirs(); FileOutputStream out = new FileOutputStream(entryFile); IOUtils.copy(tIn, out); out.close(); entryFile.setLastModified(entry.getModTime().getTime()); } } while (true); tIn.close(); in.close(); fin.close(); for (Map.Entry<String, Long> moddi : modDateMap.entrySet()) { String key = moddi.getKey(); Long value = moddi.getValue(); (new File(key)).setLastModified(value); } }
From source file:adams.core.io.TarUtils.java
/** * Decompresses the specified file from a tar file. * * @param input the tar file to decompress * @param archiveFile the file from the archive to extract * @param output the name of the output file * @param createDirs whether to create the directory structure represented * by output file//from w w w . ja v a 2 s . c o m * @param bufferSize the buffer size to use * @param errors for storing potential errors * @return whether file was successfully extracted */ public static boolean decompress(File input, String archiveFile, File output, boolean createDirs, int bufferSize, StringBuilder errors) { boolean result; FileInputStream fis; TarArchiveInputStream archive; TarArchiveEntry entry; File outFile; String outName; byte[] buffer; FileOutputStream fos; BufferedOutputStream out; int len; String error; long size; long read; result = false; archive = null; fis = null; fos = null; try { // decompress archive buffer = new byte[bufferSize]; fis = new FileInputStream(input.getAbsoluteFile()); archive = openArchiveForReading(input, fis); while ((entry = archive.getNextTarEntry()) != null) { if (entry.isDirectory()) continue; if (!entry.getName().equals(archiveFile)) continue; out = null; outName = null; try { // output name outName = output.getAbsolutePath(); // create directory, if necessary outFile = new File(outName).getParentFile(); if (!outFile.exists()) { if (!createDirs) { error = "Output directory '" + outFile.getAbsolutePath() + " does not exist', " + "skipping extraction of '" + outName + "'!"; System.err.println(error); errors.append(error + "\n"); break; } else { if (!outFile.mkdirs()) { error = "Failed to create directory '" + outFile.getAbsolutePath() + "', " + "skipping extraction of '" + outName + "'!"; System.err.println(error); errors.append(error + "\n"); break; } } } // extract data fos = new FileOutputStream(outName); out = new BufferedOutputStream(fos, bufferSize); size = entry.getSize(); read = 0; while (read < size) { len = archive.read(buffer); read += len; out.write(buffer, 0, len); } result = true; break; } catch (Exception e) { result = false; error = "Error extracting '" + entry.getName() + "' to '" + outName + "': " + e; System.err.println(error); errors.append(error + "\n"); } finally { FileUtils.closeQuietly(out); FileUtils.closeQuietly(fos); } } } catch (Exception e) { result = false; e.printStackTrace(); errors.append("Error occurred: " + e + "\n"); } finally { FileUtils.closeQuietly(fis); if (archive != null) { try { archive.close(); } catch (Exception e) { // ignored } } } return result; }
From source file:com.playonlinux.core.utils.archive.Tar.java
/** * Uncompress a tar// w w w .ja v a 2 s .co m * * @param countingInputStream * to count the number of byte extracted * @param outputDir * The directory where files should be extracted * @return A list of extracted files * @throws ArchiveException * if the process fails */ private List<File> uncompress(final InputStream inputStream, CountingInputStream countingInputStream, final File outputDir, long finalSize, Consumer<ProgressEntity> stateCallback) { final List<File> uncompressedFiles = new LinkedList<>(); try (ArchiveInputStream debInputStream = new ArchiveStreamFactory().createArchiveInputStream("tar", inputStream)) { TarArchiveEntry entry; while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { LOGGER.info(String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath())); if (!outputFile.exists()) { LOGGER.info(String.format("Attempting to createPrefix output directory %s.", outputFile.getAbsolutePath())); Files.createDirectories(outputFile.toPath()); } } else { LOGGER.info(String.format("Creating output file %s (%s).", outputFile.getAbsolutePath(), entry.getMode())); if (entry.isSymbolicLink()) { Files.createSymbolicLink(Paths.get(outputFile.getAbsolutePath()), Paths.get(entry.getLinkName())); } else { try (final OutputStream outputFileStream = new FileOutputStream(outputFile)) { IOUtils.copy(debInputStream, outputFileStream); Files.setPosixFilePermissions(Paths.get(outputFile.getPath()), com.playonlinux.core.utils.Files.octToPosixFilePermission(entry.getMode())); } } } uncompressedFiles.add(outputFile); stateCallback.accept(new ProgressEntity.Builder() .withPercent((double) countingInputStream.getCount() / (double) finalSize * (double) 100) .withProgressText("Extracting " + outputFile.getName()).build()); } return uncompressedFiles; } catch (IOException | org.apache.commons.compress.archivers.ArchiveException e) { throw new ArchiveException("Unable to extract the file", e); } }
From source file:io.cloudslang.content.vmware.services.DeployOvfTemplateService.java
private ITransferVmdkFrom getTransferVmdK(final String templateFilePathStr, final String vmdkName) throws IOException { final Path templateFilePath = Paths.get(templateFilePathStr); if (isOva(templateFilePath)) { final TarArchiveInputStream tar = new TarArchiveInputStream(new FileInputStream(templateFilePathStr)); TarArchiveEntry entry; while ((entry = tar.getNextTarEntry()) != null) { if (new File(entry.getName()).getName().startsWith(vmdkName)) { return new TransferVmdkFromInputStream(tar, entry.getSize()); }/*from w w w . j a va2 s .com*/ } } else if (isOvf(templateFilePath)) { final Path vmdkPath = templateFilePath.getParent().resolve(vmdkName); return new TransferVmdkFromFile(vmdkPath.toFile()); } throw new RuntimeException(NOT_OVA_OR_OVF); }
From source file:CASUAL.communicationstools.heimdall.odin.OdinFile.java
/** * Extracts Odin contents to outputDir// w w w. j a v a2 s . co m * * @param outputDir temp folder * @return an array of files extracted from Odin Package * @throws IOException {@inheritDoc} * @throws ArchiveException {@inheritDoc} * @throws NoSuchAlgorithmException {@inheritDoc} */ public File[] extractOdinContents(String outputDir) throws IOException, ArchiveException, NoSuchAlgorithmException { if (files != null) { //for sucessive calls return files.toArray(new File[files.size()]); } files = new ArrayList<File>(); TarArchiveEntry entry; //parse the entries while ((entry = (TarArchiveEntry) tarStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); //make folders if (entry.isDirectory()) { if (!outputFile.exists()) { System.out.println("creating dir:" + outputFile.getCanonicalFile()); if (!outputFile.mkdirs()) { throw new IllegalStateException(); } } //create files } else { final OutputStream outputFileStream = new FileOutputStream(outputFile); System.out.println("decompressing file:" + outputFile.getCanonicalFile()); byte[] buffer = new byte[1024 * 1024]; int len; while ((len = tarStream.read(buffer)) >= 0) { outputFileStream.write(buffer, 0, len); } outputFileStream.close(); } //add files to output array files.add(outputFile); } return files.toArray(new File[files.size()]); }
From source file:com.baidu.rigel.biplatform.tesseract.util.FileUtils.java
/** * Uncompress the incoming file.//w w w. j a va 2s . c o m * * @param inFileName * Name of the file to be uncompressed * @param outFileName * Name of target */ public static String doUncompressFile(String inFileName, String outFileName) throws IOException { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_BEGIN, "doUncompressFile", "[inFileName:" + inFileName + "]")); if (StringUtils.isEmpty(inFileName)) { throw new IllegalArgumentException(); } String decompressedFileName = outFileName; File inFile = new File(inFileName); if (StringUtils.isEmpty(decompressedFileName)) { // not specified outFileName StringBuilder sb = new StringBuilder(); sb.append(inFile.getParentFile().getAbsolutePath()); sb.append(File.separator); // sb.append(inFile.getName().substring(0, // inFile.getName().indexOf("."))); // sb.append(File.separator); decompressedFileName = sb.toString(); } File outFile = new File(decompressedFileName); if (!outFile.exists()) { outFile.mkdirs(); } /** * create a TarArchiveInputStream object. */ FileInputStream fin = null; BufferedInputStream in = null; GzipCompressorInputStream gzIn = null; TarArchiveInputStream tarIn = null; FileOutputStream fos = null; BufferedOutputStream dest = null; TarArchiveEntry entry = null; try { fin = new FileInputStream(inFile); in = new BufferedInputStream(fin); gzIn = new GzipCompressorInputStream(in); tarIn = new TarArchiveInputStream(gzIn); /** * Read the tar entries using the getNextEntry method */ while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_DECOMPRESS_PROCESS, "Extracting File:" + entry.getName())); if (entry.isDirectory()) { /** * If the entry is a directory, create the directory. */ File f = new File(decompressedFileName + entry.getName()); f.mkdirs(); } else { /** * If the entry is a file,write the decompressed file to the * disk and close destination stream. */ int count; byte[] data = new byte[TesseractConstant.FILE_BLOCK_SIZE]; String fileName = decompressedFileName + entry.getName().substring( entry.getName().indexOf(TesseractConstant.DECOMPRESSION_FILENAME_SPLITTER) + 1); fos = new FileOutputStream(new File(fileName)); dest = new BufferedOutputStream(fos, TesseractConstant.FILE_BLOCK_SIZE); while ((count = tarIn.read(data, 0, TesseractConstant.FILE_BLOCK_SIZE)) != -1) { dest.write(data, 0, count); } dest.close(); } } /** * Close the input stream */ tarIn.close(); } catch (IOException e) { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_DECOMPRESS_ERROR, "IOException")); LOGGER.error(e.getMessage(), e); throw e; } finally { try { fin.close(); in.close(); gzIn.close(); tarIn.close(); fos.close(); dest.close(); } catch (IOException e) { LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_DECOMPRESS_ERROR, "IOException occur when closing fd")); LOGGER.error(e.getMessage(), e); throw e; } } LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "doUncompressFile", "[inFileName:" + inFileName + "]")); return decompressedFileName; }
From source file:at.ac.tuwien.big.testsuite.impl.task.UnzipTaskImpl.java
private void untar(File tarFile, File baseDirectory, Collection<Exception> exceptions, boolean gzipped) { try (FileInputStream fis = new FileInputStream(tarFile); TarArchiveInputStream tis = new TarArchiveInputStream( gzipped ? new GzipCompressorInputStream(fis) : fis)) { TarArchiveEntry entry; while ((entry = tis.getNextTarEntry()) != null) { String escapedEntryName = escapeFileName(entry.getName()); File entryFile = new File(baseDirectory, escapedEntryName); if (entry.isDirectory()) { if (!contains(entryFile.getAbsolutePath(), ignoredDirectories)) { entryFile.mkdir();//from w ww.ja v a2 s . c o m } } else if (!endsWith(entryFile.getName(), ignoredExtensions) && !contains(entryFile.getAbsolutePath(), ignoredDirectories)) { if (entryFile.getAbsolutePath().indexOf(File.separatorChar, baseDirectory.getAbsolutePath().length()) > -1) { // Only create dirs if file is not in the root dir entryFile.getParentFile().mkdirs(); } try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(entryFile))) { copyInputStream(tis, outputStream); } } addTotalWork(1); addDoneWork(1); } } catch (Exception ex) { exceptions.add(ex); } }
From source file:io.cloudslang.content.vmware.services.DeployOvfTemplateService.java
@NotNull private String getOvfTemplateAsString(final String templatePath) throws IOException { if (isOva(Paths.get(templatePath))) { try (final TarArchiveInputStream tar = new TarArchiveInputStream(new FileInputStream(templatePath))) { TarArchiveEntry entry; while ((entry = tar.getNextTarEntry()) != null) { if (isOvf(Paths.get(new File(entry.getName()).getName()))) { return OvfUtils.writeToString(tar, entry.getSize()); }//from w w w . j a v a 2s . c o m } } } else if (isOvf(Paths.get(templatePath))) { final InputStream inputStream = new FileInputStream(templatePath); return IOUtils.toString(inputStream, UTF_8); } throw new RuntimeException(FILE_COULD_NOT_BE_READ); }
From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java
private void extractEntry(TarArchiveInputStream tar, File destination, TarArchiveEntry entry) throws IOException { File file = new File(destination, entry.getName()); if (entry.isDirectory()) { file.mkdirs();/*from w ww. ja v a 2s .c o m*/ } else { try (FileOutputStream fos = new FileOutputStream(file)) { logger.debug("Extracting {} to {}", entry.getName(), file.getAbsoluteFile()); IOUtils.copy(tar, fos); } } }
From source file:de.uzk.hki.da.pkg.ArchiveBuilder.java
/** * Unpacks the contents of the given archive into the given folder * /*from ww w . ja v a 2s . c om*/ * @param srcFile The archive container file * @param destFolder The destination folder * @param uncompress Indicates if the archive file is compressed (tgz file) or not (tar file) * @throws Exception */ public void unarchiveFolder(File srcFile, File destFolder, boolean uncompress) throws Exception { FileInputStream fIn = new FileInputStream(srcFile); BufferedInputStream in = new BufferedInputStream(fIn); TarArchiveInputStream tIn = null; GzipCompressorInputStream gzIn = null; if (uncompress) { gzIn = new GzipCompressorInputStream(in); tIn = new TarArchiveInputStream(gzIn); } else tIn = new TarArchiveInputStream(fIn); TarArchiveEntry entry; do { entry = tIn.getNextTarEntry(); if (entry == null) break; File entryFile = new File(destFolder.getAbsolutePath() + "/" + entry.getName()); if (entry.isDirectory()) entryFile.mkdirs(); else { new File(entryFile.getAbsolutePath().substring(0, entryFile.getAbsolutePath().lastIndexOf('/'))) .mkdirs(); FileOutputStream out = new FileOutputStream(entryFile); IOUtils.copy(tIn, out); out.close(); } } while (true); tIn.close(); if (gzIn != null) gzIn.close(); in.close(); fIn.close(); }