Java Code Examples for org.apache.commons.compress.archivers.tar.TarArchiveEntry

The following examples show how to use org.apache.commons.compress.archivers.tar.TarArchiveEntry. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: tutorials   Source File: Utils.java    License: MIT License 7 votes vote down vote up
/**
 * Extract a "tar.gz" file into a given folder.
 * @param file
 * @param folder 
 */
public static void extractTarArchive(File file, String folder) throws IOException {
    logger.info("Extracting archive {} into folder {}", file.getName(), folder);
    // @formatter:off
    try (FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        GzipCompressorInputStream gzip = new GzipCompressorInputStream(bis); 
        TarArchiveInputStream tar = new TarArchiveInputStream(gzip)) {
   // @formatter:on
        TarArchiveEntry entry;
        while ((entry = (TarArchiveEntry) tar.getNextEntry()) != null) {
            extractEntry(entry, tar, folder);
        }
    }
  logger.info("Archive extracted"); 
}
 
Example 2
@Override
protected void processInputStream(final InputStream stream, final FlowFile tarArchivedFlowFile, final Writer writer) throws IOException {
    try (final TarArchiveInputStream tarIn = new TarArchiveInputStream(new BufferedInputStream(stream))) {
        TarArchiveEntry tarEntry;
        while ((tarEntry = tarIn.getNextTarEntry()) != null) {
            if (tarEntry.isDirectory()) {
                continue;
            }
            final String key = tarEntry.getName();
            final long fileSize = tarEntry.getSize();
            final InputStreamWritable inStreamWritable = new InputStreamWritable(tarIn, (int) fileSize);
            writer.append(new Text(key), inStreamWritable);
            logger.debug("Appending FlowFile {} to Sequence File", new Object[]{key});
        }
    }
}
 
Example 3
Source Project: streamline   Source File: CustomProcessorUploadHandler.java    License: Apache License 2.0 6 votes vote down vote up
private byte[] getFileAsByteArray (File tarFile, Function<String, Boolean> filterFunc) {
    byte[] data = null;
    LOG.info("Looking in to file {} ", tarFile);
    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tarFile));
         TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(bis)) {
        TarArchiveEntry tarArchiveEntry = tarArchiveInputStream.getNextTarEntry();
        while (tarArchiveEntry != null) {
            if (filterFunc.apply(tarArchiveEntry.getName())) {
                data = IOUtils.toByteArray(tarArchiveInputStream);
                break;
            }
            tarArchiveEntry = tarArchiveInputStream.getNextTarEntry();
        }
    } catch (IOException e) {
        LOG.warn("Exception occured while looking in to tar file [] ", filterFunc, tarFile, e);
    }
    return data;
}
 
Example 4
Source Project: besu   Source File: DatabaseMigrationAcceptanceTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void extract(final Path path, final String destDirectory) throws IOException {
  try (TarArchiveInputStream fin =
      new TarArchiveInputStream(
          new GzipCompressorInputStream(new FileInputStream(path.toAbsolutePath().toString())))) {
    TarArchiveEntry entry;
    while ((entry = fin.getNextTarEntry()) != null) {
      if (entry.isDirectory()) {
        continue;
      }
      final File curfile = new File(destDirectory, entry.getName());
      final File parent = curfile.getParentFile();
      if (!parent.exists()) {
        parent.mkdirs();
      }
      IOUtils.copy(fin, new FileOutputStream(curfile));
    }
  }
}
 
Example 5
Source Project: Export   Source File: ExpProc.java    License: Apache License 2.0 6 votes vote down vote up
private void addArchive(File file, TarArchiveOutputStream aos,
		String basepath) throws Exception {
	if (file.exists()) {
		TarArchiveEntry entry = new TarArchiveEntry(basepath + "/"
				+ file.getName());
		entry.setSize(file.length());
		aos.putArchiveEntry(entry);
		BufferedInputStream bis = new BufferedInputStream(
				new FileInputStream(file));
		int count;
		byte data[] = new byte[1024];
		while ((count = bis.read(data, 0, data.length)) != -1) {
			aos.write(data, 0, count);
		}
		bis.close();
		aos.closeArchiveEntry();
	}
}
 
Example 6
Source Project: nifi   Source File: FlowFilePackagerV1.java    License: Apache License 2.0 6 votes vote down vote up
private void writeAttributesEntry(final Map<String, String> attributes, final TarArchiveOutputStream tout) throws IOException {
    final StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE properties\n  SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n");
    sb.append("<properties>");
    for (final Map.Entry<String, String> entry : attributes.entrySet()) {
        final String escapedKey = StringEscapeUtils.escapeXml11(entry.getKey());
        final String escapedValue = StringEscapeUtils.escapeXml11(entry.getValue());
        sb.append("\n  <entry key=\"").append(escapedKey).append("\">").append(escapedValue).append("</entry>");
    }
    sb.append("</properties>");

    final byte[] metaBytes = sb.toString().getBytes(StandardCharsets.UTF_8);
    final TarArchiveEntry attribEntry = new TarArchiveEntry(FILENAME_ATTRIBUTES);
    attribEntry.setMode(tarPermissions);
    attribEntry.setSize(metaBytes.length);
    tout.putArchiveEntry(attribEntry);
    tout.write(metaBytes);
    tout.closeArchiveEntry();
}
 
Example 7
Source Project: org.hl7.fhir.core   Source File: NPMPackageGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public void loadFiles(String root, File dir, String... noload) throws IOException {
  for (File f : dir.listFiles()) {
    if (!Utilities.existsInList(f.getName(), noload)) {
      if (f.isDirectory()) {
        loadFiles(root, f);
      } else {
        String path = f.getAbsolutePath().substring(root.length()+1);
        byte[] content = TextFile.fileToBytes(f);
        if (created.contains(path)) 
          System.out.println("Duplicate package file "+path);
        else {
          created.add(path);
          TarArchiveEntry entry = new TarArchiveEntry(path);
          entry.setSize(content.length);
          tar.putArchiveEntry(entry);
          tar.write(content);
          tar.closeArchiveEntry();
        }
      }
    }
  }
}
 
Example 8
@Test
public void testFileOwnershipAndPermissions() throws IOException, PackagingException {
    final File debFile = createPackage(ImmutableList.<Resource>of(
            new StringResource("hello world", true, "/test.txt", USER, USER, 0764)
    ));

    final File packageDir = temporaryFolder.newFolder();
    ArchiveUtils.extractAr(debFile, packageDir);

    try (final TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(new File(packageDir, "data.tar.gz"))))) {
        final TarArchiveEntry entry = in.getNextTarEntry();
        assertEquals("./test.txt", entry.getName());
        assertEquals(USER, entry.getUserName());
        assertEquals(USER, entry.getGroupName());
        assertEquals(0764, entry.getMode());
    }
}
 
Example 9
Source Project: localization_nifi   Source File: FlowFilePackagerV1.java    License: Apache License 2.0 6 votes vote down vote up
private void writeAttributesEntry(final Map<String, String> attributes, final TarArchiveOutputStream tout) throws IOException {
    final StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE properties\n  SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n");
    sb.append("<properties>");
    for (final Map.Entry<String, String> entry : attributes.entrySet()) {
        final String escapedKey = StringEscapeUtils.escapeXml11(entry.getKey());
        final String escapedValue = StringEscapeUtils.escapeXml11(entry.getValue());
        sb.append("\n  <entry key=\"").append(escapedKey).append("\">").append(escapedValue).append("</entry>");
    }
    sb.append("</properties>");

    final byte[] metaBytes = sb.toString().getBytes(StandardCharsets.UTF_8);
    final TarArchiveEntry attribEntry = new TarArchiveEntry(FILENAME_ATTRIBUTES);
    attribEntry.setMode(tarPermissions);
    attribEntry.setSize(metaBytes.length);
    tout.putArchiveEntry(attribEntry);
    tout.write(metaBytes);
    tout.closeArchiveEntry();
}
 
Example 10
public Future<?> setDataPath(String dataFilePath) {
    try (TarArchiveInputStream tarInput = new TarArchiveInputStream(new GZIPInputStream(
            new FileInputStream(dataFilePath)))) {

        TarArchiveEntry currentEntry;
        boolean hasDatabaseFile = false;
        while ((currentEntry = tarInput.getNextTarEntry()) != null) {
            if (currentEntry.getName().contains(DATABASE_FILE_NAME)) {
                hasDatabaseFile = true;
                break;
            }
        }
        if (!hasDatabaseFile) {
            return Future.failedFuture(String.format("Database file %s not found in %s archive", DATABASE_FILE_NAME,
                    dataFilePath));
        }

        databaseReader = new DatabaseReader.Builder(tarInput).fileMode(Reader.FileMode.MEMORY).build();
        return Future.succeededFuture();
    } catch (IOException e) {
        return Future.failedFuture(
                String.format("IO Exception occurred while trying to read an archive/db file: %s", e.getMessage()));
    }
}
 
Example 11
Source Project: dekorate   Source File: Packaging.java    License: Apache License 2.0 6 votes vote down vote up
public static void tar(Path inputPath, Path outputPath) throws IOException {
  if (!Files.exists(inputPath)) {
    throw new FileNotFoundException("File not found " + inputPath);
  }

  try (TarArchiveOutputStream tarArchiveOutputStream = buildTarStream(outputPath.toFile())) {
    if (!Files.isDirectory(inputPath)) {
      TarArchiveEntry tarEntry = new TarArchiveEntry(inputPath.toFile().getName());
      if (inputPath.toFile().canExecute()) {
        tarEntry.setMode(tarEntry.getMode() | 0755);
      }
      putTarEntry(tarArchiveOutputStream, tarEntry, inputPath);
    } else {
      Files.walkFileTree(inputPath,
                         new TarDirWalker(inputPath, tarArchiveOutputStream));
    }
    tarArchiveOutputStream.flush();
  }
}
 
Example 12
private void untar(Path archiveFile, Path project) throws IOException {
	try (TarArchiveInputStream input = new TarArchiveInputStream(
			new GzipCompressorInputStream(Files.newInputStream(archiveFile)))) {
		TarArchiveEntry entry = null;
		while ((entry = input.getNextTarEntry()) != null) {
			Path path = project.resolve(entry.getName());
			if (entry.isDirectory()) {
				Files.createDirectories(path);
			}
			else {
				Files.createDirectories(path.getParent());
				Files.write(path, StreamUtils.copyToByteArray(input));
			}
			applyPermissions(path, getPosixFilePermissions(entry.getMode()));
		}
	}
}
 
Example 13
/**
 * Get the IFileSystemObject corresponding to the specified raw object
 *
 * @param o
 *            the raw object
 * @return the corresponding IFileSystemObject
 */
public IFileSystemObject getIFileSystemObject(Object o) {
    if (o == null) {
        return null;
    }

    if (o instanceof File) {
        return new FileFileSystemObject((File) o);
    } else if (o instanceof TarArchiveEntry) {
        return new TarFileSystemObject((TarArchiveEntry) o, fArchivePath);
    } else if (o instanceof ZipArchiveEntry) {
        return new ZipFileSystemObject((ZipArchiveEntry) o, fArchivePath);
    } else if (o instanceof GzipEntry) {
        return new GzipFileSystemObject((GzipEntry) o, fArchivePath);
    }

    throw new IllegalArgumentException("Object type not handled"); //$NON-NLS-1$
}
 
Example 14
Source Project: docker-client   Source File: CompressedDirectory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path dir,
                                         BasicFileAttributes attrs) throws IOException {
  if (Files.isSameFile(dir, root)) {
    return FileVisitResult.CONTINUE;
  }

  final Path relativePath = root.relativize(dir);

  if (exclude(ignoreMatchers, relativePath)) {
    return FileVisitResult.CONTINUE;
  }

  final TarArchiveEntry entry = new TarArchiveEntry(dir.toFile());
  entry.setName(relativePath.toString());
  entry.setMode(getFileMode(dir));
  tarStream.putArchiveEntry(entry);
  tarStream.closeArchiveEntry();
  return FileVisitResult.CONTINUE;
}
 
Example 15
Source Project: twister2   Source File: TarGzipPacker.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * given tar.gz file will be copied to this tar.gz file.
 * all files will be transferred to new tar.gz file one by one.
 * original directory structure will be kept intact
 *
 * @param zipFile the archive file to be copied to the new archive
 * @param dirPrefixForTar sub path inside the archive
 */
public boolean addZipToArchive(String zipFile, String dirPrefixForTar) {
  try {
    // construct input stream
    ZipFile zipFileObj = new ZipFile(zipFile);
    Enumeration<? extends ZipEntry> entries = zipFileObj.entries();

    // copy the existing entries from source gzip file
    while (entries.hasMoreElements()) {
      ZipEntry nextEntry = entries.nextElement();
      TarArchiveEntry entry = new TarArchiveEntry(dirPrefixForTar + nextEntry.getName());
      entry.setSize(nextEntry.getSize());
      entry.setModTime(nextEntry.getTime());

      tarOutputStream.putArchiveEntry(entry);
      IOUtils.copy(zipFileObj.getInputStream(nextEntry), tarOutputStream);
      tarOutputStream.closeArchiveEntry();
    }

    zipFileObj.close();
    return true;
  } catch (IOException ioe) {
    LOG.log(Level.SEVERE, "Archive File can not be added: " + zipFile, ioe);
    return false;
  }
}
 
Example 16
Source Project: packagedrone   Source File: DebianPackageWriter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private static void applyInfo ( final TarArchiveEntry entry, final EntryInformation entryInformation )
{
    if ( entryInformation == null )
    {
        return;
    }

    if ( entryInformation.getUser () != null )
    {
        entry.setUserName ( entryInformation.getUser () );
    }
    if ( entryInformation.getGroup () != null )
    {
        entry.setGroupName ( entryInformation.getGroup () );
    }
    entry.setMode ( entryInformation.getMode () );
}
 
Example 17
Source Project: MSPaintIDE   Source File: ExtractUtils.java    License: MIT License 6 votes vote down vote up
public static void untar(TarArchiveInputStream tarIn, File targetDir) throws IOException {
    byte[] b = new byte[4096];
    TarArchiveEntry tarEntry;
    while ((tarEntry = tarIn.getNextTarEntry()) != null) {
        final File file = new File(targetDir, tarEntry.getName());
        if (tarEntry.isDirectory()) {
            if (!file.mkdirs()) {
                throw new IOException("Unable to create folder " + file.getAbsolutePath());
            }
        } else {
            final File parent = file.getParentFile();
            if (!parent.exists()) {
                if (!parent.mkdirs()) {
                    throw new IOException("Unable to create folder " + parent.getAbsolutePath());
                }
            }
            try (FileOutputStream fos = new FileOutputStream(file)) {
                int r;
                while ((r = tarIn.read(b)) != -1) {
                    fos.write(b, 0, r);
                }
            }
        }
    }
}
 
Example 18
/**
 * Wraps the parent stream into TarInputStream 
 * and positions it to read the given entry (no wildcards are applicable).
 * 
 * If no entry is given, the stream is positioned to read the first file entry.
 * 
 * @param parentStream
 * @param entryName
 * @return
 * @throws IOException
 */
public static TarArchiveInputStream getTarInputStream(InputStream parentStream, String entryName) throws IOException {
    TarArchiveInputStream tis = new TarArchiveInputStream(parentStream) ;     
    TarArchiveEntry entry;

    // find a matching entry
    while ((entry = tis.getNextTarEntry()) != null) {
    	if (entry.isDirectory()) {
    		continue; // CLS-537: skip directories, we want to read the first file
    	}
    	// when url is given without anchor; first entry in tar file is used
        if (StringUtils.isEmpty(entryName) || entry.getName().equals(entryName)) {
           	return tis;
        }
    }
    
    //no entry found report
    throw new IOException("Wrong anchor (" + entryName + ") to tar file.");
}
 
Example 19
Source Project: vertx-starter   Source File: GeneratorService.java    License: Apache License 2.0 6 votes vote down vote up
private void addFile(Path rootPath, Path filePath, ArchiveOutputStream stream) throws IOException {
  String relativePath = rootPath.relativize(filePath).toString();
  if (relativePath.length() == 0) return;
  String entryName = jarFileWorkAround(leadingDot(relativePath));
  ArchiveEntry entry = stream.createArchiveEntry(filePath.toFile(), entryName);
  if (EXECUTABLES.contains(entryName)) {
    if (entry instanceof ZipArchiveEntry) {
      ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) entry;
      zipArchiveEntry.setUnixMode(0744);
    } else if (entry instanceof TarArchiveEntry) {
      TarArchiveEntry tarArchiveEntry = (TarArchiveEntry) entry;
      tarArchiveEntry.setMode(0100744);
    }
  }
  stream.putArchiveEntry(entry);
  if (filePath.toFile().isFile()) {
    try (InputStream i = Files.newInputStream(filePath)) {
      IOUtils.copy(i, stream);
    }
  }
  stream.closeArchiveEntry();
}
 
Example 20
Source Project: docker-client   Source File: CompressedDirectoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFileWithEmptyDirectory() throws Exception {
  Path tempDir = Files.createTempDirectory("dockerDirectoryEmptySubdirectory");
  tempDir.toFile().deleteOnExit();
  assertThat(new File(tempDir.toFile(), "emptySubDir").mkdir(), is(true));

  try (CompressedDirectory dir = CompressedDirectory.create(tempDir);
       BufferedInputStream fileIn = new BufferedInputStream(Files.newInputStream(dir.file()));
       GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(fileIn);
       TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) {

    final List<String> names = new ArrayList<>();
    TarArchiveEntry entry;
    while ((entry = tarIn.getNextTarEntry()) != null) {
      final String name = entry.getName();
      names.add(name);
    }
    assertThat(names, contains("emptySubDir/"));
  }
}
 
Example 21
Source Project: zeppelin   Source File: TarUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static void addToArchiveCompression(TarArchiveOutputStream out, File file, String dir)
    throws IOException {
  if (file.isFile()){
    String archivePath = "." + dir;
    LOGGER.info("archivePath = " + archivePath);
    out.putArchiveEntry(new TarArchiveEntry(file, archivePath));
    try (FileInputStream in = new FileInputStream(file)) {
      IOUtils.copy(in, out);
    }
    out.closeArchiveEntry();
  } else if (file.isDirectory()) {
    File[] children = file.listFiles();
    if (children != null){
      for (File child : children){
        String appendDir = child.getAbsolutePath().replace(file.getAbsolutePath(), "");
        addToArchiveCompression(out, child, dir + appendDir);
      }
    }
  } else {
    LOGGER.error(file.getName() + " is not supported");
  }
}
 
Example 22
Source Project: cs-actions   Source File: DeployOvfTemplateService.java    License: Apache License 2.0 6 votes vote down vote up
@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());
                }
            }
        }
    } 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);
}
 
Example 23
Source Project: kubernetes-client   Source File: PodUpload.java    License: Apache License 2.0 6 votes vote down vote up
private static void addFileToTar(String rootTarPath, File file, TarArchiveOutputStream tar)
  throws IOException {

  final String fileName =
    Optional.ofNullable(rootTarPath).orElse("") + TAR_PATH_DELIMITER + file.getName();
  tar.putArchiveEntry(new TarArchiveEntry(file, fileName));
  if (file.isFile()) {
    Files.copy(file.toPath(), tar);
    tar.closeArchiveEntry();
  } else if (file.isDirectory()) {
    tar.closeArchiveEntry();
    for (File fileInDirectory : file.listFiles()) {
      addFileToTar(fileName, fileInDirectory, tar);
    }
  }
}
 
Example 24
Source Project: jarchivelib   Source File: AttributeAccessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Detects the type of the given ArchiveEntry and returns an appropriate AttributeAccessor for it.
 * 
 * @param entry the adaptee
 * @return a new attribute accessor instance
 */
public static AttributeAccessor<?> create(ArchiveEntry entry) {
    if (entry instanceof TarArchiveEntry) {
        return new TarAttributeAccessor((TarArchiveEntry) entry);
    } else if (entry instanceof ZipArchiveEntry) {
        return new ZipAttributeAccessor((ZipArchiveEntry) entry);
    } else if (entry instanceof CpioArchiveEntry) {
        return new CpioAttributeAccessor((CpioArchiveEntry) entry);
    } else if (entry instanceof ArjArchiveEntry) {
        return new ArjAttributeAccessor((ArjArchiveEntry) entry);
    } else if (entry instanceof ArArchiveEntry) {
        return new ArAttributeAccessor((ArArchiveEntry) entry);
    }

    return new FallbackAttributeAccessor(entry);
}
 
Example 25
Source Project: cs-actions   Source File: DeployOvfTemplateService.java    License: Apache License 2.0 6 votes vote down vote up
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());
            }
        }
    } else if (isOvf(templateFilePath)) {
        final Path vmdkPath = templateFilePath.getParent().resolve(vmdkName);
        return new TransferVmdkFromFile(vmdkPath.toFile());
    }
    throw new RuntimeException(NOT_OVA_OR_OVF);
}
 
Example 26
Source Project: fabric-sdk-java   Source File: LifecycleChaincodePackage.java    License: Apache License 2.0 6 votes vote down vote up
public JsonObject getMetaInfJson() throws IOException {

        try (TarArchiveInputStream tarInput = new TarArchiveInputStream(new GzipCompressorInputStream(new ByteArrayInputStream(pBytes)))) {

            TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
            while (currentEntry != null) {
                if (currentEntry.getName().equals("metadata.json")) {
                    byte[] buf = new byte[(int) currentEntry.getSize()];
                    tarInput.read(buf, 0, (int) currentEntry.getSize());

                    try (InputStream stream = new ByteArrayInputStream(buf)) {
                        try (JsonReader reader = Json.createReader(stream)) {

                            return (JsonObject) reader.read();
                        }
                    }

                }
                currentEntry = tarInput.getNextTarEntry();

            }
        }

        return null;
    }
 
Example 27
Source Project: incubator-heron   Source File: FileHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static void addFileToArchive(TarArchiveOutputStream archiveOutputStream, File file,
                                     String base) throws IOException {
  final File absoluteFile = file.getAbsoluteFile();
  final String entryName = base + file.getName();
  final TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(file, entryName);
  archiveOutputStream.putArchiveEntry(tarArchiveEntry);

  if (absoluteFile.isFile()) {
    Files.copy(file.toPath(), archiveOutputStream);
    archiveOutputStream.closeArchiveEntry();
  } else {
    archiveOutputStream.closeArchiveEntry();
    if (absoluteFile.listFiles() != null) {
      for (File f : absoluteFile.listFiles()) {
        addFileToArchive(archiveOutputStream, f, entryName + "/");
      }
    }
  }
}
 
Example 28
Source Project: Export   Source File: Gzip.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * ��һ���ļ��鵵
 * 
 * @param sources
 *            Ҫ�鵵��ԭ�ļ�����
 * @param target
 *            �鵵����ļ�
 * @return File ���ع鵵����ļ�
 * @throws Exception
 */
public static File tar(File[] sources, File target) throws Exception {
	FileOutputStream out = new FileOutputStream(target);
	TarArchiveOutputStream os = new TarArchiveOutputStream(out);
	for (File file : sources) {
		os.putArchiveEntry(new TarArchiveEntry(file));
		IOUtils.copy(new FileInputStream(file), os);
		os.closeArchiveEntry();
	}
	if (os != null) {
		os.flush();
		os.close();
	}
	return target;
}
 
Example 29
@Override
public List<FileEntry> getFileEntries(Path folder) throws IOException {
    TarArchiveInputStream inputStream = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(folder.toFile())));
    TarArchiveEntry entry;
    List<FileEntry> files = new ArrayList<>();
    while ((entry = inputStream.getNextTarEntry()) != null) {
        files.add(createFileEntry(entry));
    }
    return files;
}
 
Example 30
static void writeArchiveEntry(final ArchiveOutputStream archive, final String name, final byte[] bytes) throws IOException {
    final TarArchiveEntry entry = new TarArchiveEntry(name);
    entry.setSize(bytes.length);
    archive.putArchiveEntry(entry);
    archive.write(bytes);
    archive.closeArchiveEntry();
}