Java Code Examples for org.apache.commons.compress.archivers.zip.ZipFile

The following examples show how to use org.apache.commons.compress.archivers.zip.ZipFile. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: buck   Source File: ZipRuleIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldZipSources() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp);
  workspace.setUp();

  Path zip = workspace.buildAndReturnOutput("//example:ziptastic");

  // Make sure we have the right files and attributes.
  try (ZipFile zipFile = new ZipFile(zip.toFile())) {
    ZipArchiveEntry cake = zipFile.getEntry("cake.txt");
    assertThat(cake, Matchers.notNullValue());
    assertFalse(cake.isUnixSymlink());
    assertFalse(cake.isDirectory());

    ZipArchiveEntry beans = zipFile.getEntry("beans/");
    assertThat(beans, Matchers.notNullValue());
    assertFalse(beans.isUnixSymlink());
    assertTrue(beans.isDirectory());

    ZipArchiveEntry cheesy = zipFile.getEntry("beans/cheesy.txt");
    assertThat(cheesy, Matchers.notNullValue());
    assertFalse(cheesy.isUnixSymlink());
    assertFalse(cheesy.isDirectory());
  }
}
 
Example 2
Source Project: buck   Source File: ZipRuleIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUnpackContentsOfZipSources() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp);
  workspace.setUp();

  Path zip = workspace.buildAndReturnOutput("//example:zipsources");

  try (ZipFile zipFile = new ZipFile(zip.toFile())) {
    ZipArchiveEntry menu = zipFile.getEntry("menu.txt");
    assertThat(menu, Matchers.notNullValue());
    assertFalse(menu.isUnixSymlink());
    assertFalse(menu.isDirectory());
    ZipArchiveEntry cake = zipFile.getEntry("cake.txt");
    assertThat(cake, Matchers.notNullValue());
    assertFalse(cake.isUnixSymlink());
    assertFalse(cake.isDirectory());
  }
}
 
Example 3
Source Project: ghidra   Source File: ExtensionUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Given a zip file, returns the {@link Properties} defined in the embedded extension.properties file. 
 * 
 * @param file the extension archive file
 * @return the properties file, or null if doesn't exist
 * @throws ExtensionException if there's a problem unpacking the zip file
 */
public static Properties getPropertiesFromArchive(File file) throws ExtensionException {

	try (ZipFile zipFile = new ZipFile(file)) {
		Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
		while (zipEntries.hasMoreElements()) {
			ZipArchiveEntry entry = zipEntries.nextElement();
			if (entry.getName().endsWith(PROPERTIES_FILE_NAME)) {
				final InputStream propFile = zipFile.getInputStream(entry);
				Properties prop = new Properties();
				prop.load(propFile);
				return prop;
			}
		}

		return null;
	}
	catch (IOException e) {
		throw new ExtensionException(e.getMessage(), ExtensionExceptionType.ZIP_ERROR);
	}
}
 
Example 4
Source Project: gradle-golang-plugin   Source File: ArchiveUtils.java    License: Mozilla Public License 2.0 6 votes vote down vote up
public static void unZip(Path file, Path target) throws IOException {
    try (final ZipFile zipFile = new ZipFile(file.toFile())) {
        final Enumeration<ZipArchiveEntry> files = zipFile.getEntriesInPhysicalOrder();
        while (files.hasMoreElements()) {
            final ZipArchiveEntry entry = files.nextElement();
            final Path entryFile = target.resolve(REMOVE_LEADING_GO_PATH_PATTERN.matcher(entry.getName()).replaceFirst("")).toAbsolutePath();
            if (entry.isDirectory()) {
                createDirectoriesIfRequired(entryFile);
            } else {
                ensureParentOf(entryFile);
                try (final InputStream is = zipFile.getInputStream(entry)) {
                    try (final OutputStream os = newOutputStream(entryFile)) {
                        copy(is, os);
                    }
                }
            }
        }
    }
}
 
Example 5
Source Project: spring-boot   Source File: CompressExample.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 把一个ZIP文件解压到一个指定的目录中
 * @param zipfilename ZIP文件抽象地址
 * @param outputdir 目录绝对地址
 */
public static void unZipToFolder(String zipfilename, String outputdir) throws IOException {
    File zipfile = new File(zipfilename);
    if (zipfile.exists()) {
        outputdir = outputdir + File.separator;
        FileUtils.forceMkdir(new File(outputdir));

        ZipFile zf = new ZipFile(zipfile, "UTF-8");
        Enumeration zipArchiveEntrys = zf.getEntries();
        while (zipArchiveEntrys.hasMoreElements()) {
            ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) zipArchiveEntrys.nextElement();
            if (zipArchiveEntry.isDirectory()) {
                FileUtils.forceMkdir(new File(outputdir + zipArchiveEntry.getName() + File.separator));
            } else {
                IOUtils.copy(zf.getInputStream(zipArchiveEntry), FileUtils.openOutputStream(new File(outputdir + zipArchiveEntry.getName())));
            }
        }
    } else {
        throw new IOException("指定的解压文件不存在:\t" + zipfilename);
    }
}
 
Example 6
Source Project: embedded-rabbitmq   Source File: BasicExtractor.java    License: Apache License 2.0 6 votes vote down vote up
private void extractZip(ZipFile zipFile) {
  Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
  while (entries.hasMoreElements()) {

    ZipArchiveEntry entry = entries.nextElement();
    String fileName = entry.getName();
    File outputFile = new File(config.getExtractionFolder(), fileName);

    if (entry.isDirectory()) {
      makeDirectory(outputFile);
    } else {
      createNewFile(outputFile);
      try {
        InputStream inputStream = zipFile.getInputStream(entry);
        extractFile(inputStream, outputFile, fileName);
      } catch (IOException e) {
        throw new ExtractionException("Error extracting file '" + fileName + "' "
            + "from downloaded file: " + config.getDownloadTarget(), e);
      }
    }
  }
}
 
Example 7
Source Project: yes-cart   Source File: ZipUtils.java    License: Apache License 2.0 6 votes vote down vote up
private void unzipEntry(final ZipFile zipfile, final ZipArchiveEntry entry, final File outputDir) throws IOException {

        if (entry.isDirectory()) {
            createDir(new File(outputDir, entry.getName()));
            return;
        }

        File outputFile = new File(outputDir, entry.getName());
        if (!outputFile.getParentFile().exists()) {
            createDir(outputFile.getParentFile());
        }

        try (BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
             BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
            IOUtils.copy(inputStream, outputStream);
        }
    }
 
Example 8
Source Project: zxpoly   Source File: Spec256Arch.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static FoundSna findSna(final byte[] zipArchive) throws IOException {
  try (ZipFile zipFile = new ZipFile(new SeekableInMemoryByteChannel(zipArchive))) {
    final Enumeration<ZipArchiveEntry> iterator = zipFile.getEntries();
    while (iterator.hasMoreElements()) {
      final ZipArchiveEntry entry = iterator.nextElement();
      if (entry.isDirectory()) {
        continue;
      }
      final String name = entry.getName().replace('\\', '/').toLowerCase(Locale.ENGLISH);
      if (name.endsWith(".sna")) {
        final Matcher matcher = SNA_NAME_PATTERN.matcher(name);
        if (!matcher.find()) {
          throw new IOException("Unexpected SNA name: " + name);
        }
        String parsedSnaName = matcher.group(1);
        final byte[] snaFileBody = readData(zipFile, entry);
        return new FoundSna(
            parsedSnaName,
            snaFileBody,
            new SNAParser().read(new JBBPBitInputStream(new ByteArrayInputStream(snaFileBody)))
        );
      }
    }
  }
  return null;
}
 
Example 9
private static void extractZipFile(final File destination, final ZipFile zipFile) throws IOException {
    final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

    while (entries.hasMoreElements()) {
        final ZipArchiveEntry entry = entries.nextElement();
        final File entryDestination = getDestinationFile(destination, entry.getName());

        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            entryDestination.getParentFile().mkdirs();
            final InputStream in = zipFile.getInputStream(entry);
            try (final OutputStream out = new FileOutputStream(entryDestination)) {
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
            }
        }
    }
}
 
Example 10
Source Project: buck   Source File: ZipRuleIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotMergeSourceJarsIfRequested() throws Exception {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "zip-merge", tmp);
  workspace.setUp();

  Path zip = workspace.buildAndReturnOutput("//example:no-merge");

  // Gather expected file names
  Path sourceJar = workspace.buildAndReturnOutput("//example:cake#src");
  Path actualJar = workspace.buildAndReturnOutput("//example:cake");

  try (ZipFile zipFile = new ZipFile(zip.toFile())) {
    ZipArchiveEntry item = zipFile.getEntry(sourceJar.getFileName().toString());
    assertThat(item, Matchers.notNullValue());

    item = zipFile.getEntry(actualJar.getFileName().toString());
    assertThat(item, Matchers.notNullValue());

    item = zipFile.getEntry("cake.txt");
    assertThat(item, Matchers.notNullValue());
  }
}
 
Example 11
Source Project: buck   Source File: DefaultProjectFilesystemTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateZipPreservesExecutablePermissions() throws IOException {

  // Create a empty executable file.
  Path exe = tmp.newFile("test.exe");
  MostFiles.makeExecutable(exe);

  // Archive it into a zipfile using `Zip.create`.
  Path zipFile = tmp.getRoot().resolve("test.zip");
  Zip.create(filesystem, ImmutableList.of(exe), zipFile);

  // Now unpack the archive (using apache's common-compress, as it preserves
  // executable permissions) and verify that the archive entry has executable
  // permissions.
  try (ZipFile zip = new ZipFile(zipFile.toFile())) {
    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    assertTrue(entries.hasMoreElements());
    ZipArchiveEntry entry = entries.nextElement();
    Set<PosixFilePermission> permissions =
        MorePosixFilePermissions.fromMode(entry.getExternalAttributes() >> 16);
    assertTrue(permissions.contains(PosixFilePermission.OWNER_EXECUTE));
    assertFalse(entries.hasMoreElements());
  }
}
 
Example 12
Source Project: james-project   Source File: ZipAssertTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void isDirectoryShouldNotThrowWhenDirectory() throws Exception {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {

        ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new Directory("any"), DIRECTORY_NAME);
        archiveOutputStream.putArchiveEntry(archiveEntry);
        archiveOutputStream.closeArchiveEntry();
        archiveOutputStream.finish();
    }

    try (ZipFile zipFile = new ZipFile(destination)) {
        assertThatCode(() -> assertThatZip(zipFile)
                .containsOnlyEntriesMatching(
                    hasName(DIRECTORY_NAME)
                        .isDirectory()))
            .doesNotThrowAnyException();
    }
}
 
Example 13
Source Project: james-project   Source File: ZipAssertTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void containsOnlyExtraFieldsShouldNotThrowWhenUnexpectedField() throws Exception {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {

        ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new File("any"), ENTRY_NAME);
        archiveEntry.addExtraField(EXTRA_FIELD);
        archiveOutputStream.putArchiveEntry(archiveEntry);
        IOUtils.copy(new ByteArrayInputStream(ENTRY_CONTENT), archiveOutputStream);
        archiveOutputStream.closeArchiveEntry();

        archiveOutputStream.finish();
    }

    try (ZipFile zipFile = new ZipFile(destination)) {
        assertThatCode(() -> assertThatZip(zipFile)
            .containsOnlyEntriesMatching(
                hasName(ENTRY_NAME)
                    .containsExtraFields()))
            .doesNotThrowAnyException();
    }
}
 
Example 14
Source Project: io   Source File: BarFileValidateTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * barファイル内エントリのファイルサイズ上限値を超えた場合に例外が発生すること.
 */
@Test
public void barファイル内エントリのファイルサイズ上限値を超えた場合に例外が発生すること() {
    TestBarInstaller testBarInstaller = new TestBarInstaller();
    URL fileUrl = ClassLoader.getSystemResource("requestData/barInstall/V1_1_2_bar_minimum.bar");
    File file = new File(fileUrl.getPath());

    try {
        ZipFile zipFile = new ZipFile(file, "UTF-8");
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        long maxBarEntryFileSize = 0;
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zae = entries.nextElement();
            if (zae.isDirectory()) {
                continue;
            }
            testBarInstaller.checkBarFileEntrySize(zae, zae.getName(), maxBarEntryFileSize);
        }
        fail("Unexpected exception");
    } catch (DcCoreException dce) {
        String code = DcCoreException.BarInstall.BAR_FILE_ENTRY_SIZE_TOO_LARGE.getCode();
        assertEquals(code, dce.getCode());
    } catch (Exception ex) {
        fail("Unexpected exception");
    }
}
 
Example 15
Source Project: james-project   Source File: ZipAssertTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void hasSameContentShouldThrowWhenEntryHasDifferentExtraFieldsSize() throws Exception {
    ZipEntryWithContent expectedEntry = entryBuilder().name(ENTRY_NAME).content(ENTRY_CONTENT)
        .addField(new UidExtraField(1L))
        .addField(new UidExtraField(2L))
        .build();

    ZipEntryWithContent assertedEntry = entryBuilder().name(ENTRY_NAME).content(ENTRY_CONTENT)
        .addField(new UidExtraField(1L))
        .build();

    try (ZipFile expectedZipFile = zipFile(destination, expectedEntry);
            ZipFile assertedZipFile = zipFile(destination2, assertedEntry)) {
        assertThatThrownBy(() -> assertThatZip(assertedZipFile)
            .hasSameContentWith(expectedZipFile))
            .isInstanceOf(AssertionError.class);
    }
}
 
Example 16
Source Project: james-project   Source File: ZipAssertTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void hasSameContentShouldThrowWhenEntryHasSameExtraFieldsSizeButDifferentOrder() throws Exception {
    ZipEntryWithContent expectedEntry = entryBuilder().name(ENTRY_NAME).content(ENTRY_CONTENT)
        .addField(new UidExtraField(1L))
        .addField(new SizeExtraField(2L))
        .build();

    ZipEntryWithContent assertedEntry = entryBuilder().name(ENTRY_NAME).content(ENTRY_CONTENT)
        .addField(new SizeExtraField(2L))
        .addField(new UidExtraField(1L))
        .build();

    try (ZipFile expectedZipFile = zipFile(destination, expectedEntry);
            ZipFile assertedZipFile = zipFile(destination2, assertedEntry)) {
        assertThatThrownBy(() -> assertThatZip(assertedZipFile)
            .hasSameContentWith(expectedZipFile))
            .isInstanceOf(AssertionError.class);
    }
}
 
Example 17
private void unzip(Path archiveFile, Path project) throws IOException {
	try (ZipFile zip = new ZipFile(archiveFile.toFile())) {
		Enumeration<? extends ZipArchiveEntry> entries = zip.getEntries();
		while (entries.hasMoreElements()) {
			ZipArchiveEntry entry = entries.nextElement();
			Path path = project.resolve(entry.getName());
			if (entry.isDirectory()) {
				Files.createDirectories(path);
			}
			else {
				Files.createDirectories(path.getParent());
				Files.write(path, StreamUtils.copyToByteArray(zip.getInputStream(entry)));
			}
			applyPermissions(path, getPosixFilePermissions(entry.getUnixMode()));
		}
	}
}
 
Example 18
Source Project: translationstudio8   Source File: Mq2Xliff.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 解析 memoQ 的源文件,并将内容拷贝至骨架文件中
 * @param mqZip
 * @param hsSkeleton	R8 hsxliff的骨架文件
 * @throws Exception
 */
private void parseMQZip(String mqZip, String hsSkeleton) throws Exception{
	ZipFile zipFile = new ZipFile(new File(mqZip), "utf-8");
	Enumeration<?> e = zipFile.getEntries();
	byte ch[] = new byte[1024];
	String outputFile = "";
	File mqSklTempFile = File.createTempFile("tempskl", "skl");
	mqSklTempFile.deleteOnExit();
	while (e.hasMoreElements()) {
		ZipArchiveEntry zipEntry = (ZipArchiveEntry) e.nextElement();
		if ("document.mqxliff".equals(zipEntry.getName())) {
			outputFile = hsSkeleton;
		}else {
			outputFile = mqSklTempFile.getAbsolutePath();
		}
		File zfile = new File(outputFile);
		FileOutputStream fouts = new FileOutputStream(zfile);
		InputStream in = zipFile.getInputStream(zipEntry);
		int i;
		while ((i = in.read(ch)) != -1)
			fouts.write(ch, 0, i);
		fouts.close();
		in.close();
	}
	
	//解析r8骨加文件,并把 mq 的骨架信息添加到 r8 的骨架文件中
	parseHSSkeletonFile();
	copyMqSklToHsSkl(mqSklTempFile);
}
 
Example 19
Source Project: MyBox   Source File: CompressTools.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> readEntriesZip(File srcFile) {
        try {
            if (srcFile == null) {
                return null;
            }

            Map<String, Object> unarchive;
            try ( ZipFile zipFile = new ZipFile(srcFile)) {

                List<FileInformation> fileEntries = new ArrayList();
                Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
                while (entries.hasMoreElements()) {
                    ZipArchiveEntry entry = entries.nextElement();
                    FileInformation file = new FileInformation();
                    file.setFileName(entry.getName());
                    file.setModifyTime(entry.getLastModifiedDate().getTime());
                    file.setFileSize(entry.getSize());
                    file.setFileType(entry.isDirectory() ? "dir" : "file");
                    fileEntries.add(file);
                }
                unarchive = new HashMap<>();
                unarchive.put("archiver", ArchiveStreamFactory.ZIP);
                unarchive.put("entries", fileEntries);
            }
            return unarchive;
        } catch (Exception e) {
//            logger.debug(e.toString());
            return null;
        }
    }
 
Example 20
public void startImport()
{
    log("Importing from zip file " + file.getAbsolutePath());
    try
    {
        // NOTE: This encoding allows us to workaround bug...
        //       http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4820807
        zipFile = new ZipFile(file, "UTF-8");
    }
    catch(IOException e)
    {
        throw new ImporterException("Failed to read zip file due to " + e.getMessage(), e);
    }
}
 
Example 21
Source Project: atlas   Source File: ZipUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * isZipFile.
 * </p>
 *
 * @param zipFile a {@link java.io.File} object.
 * @return a boolean.
 */
public static boolean isZipFile(File zipFile) {
    try {
        ZipFile zf = new ZipFile(zipFile);
        boolean isZip = zf.getEntries().hasMoreElements();
        zf.close();
        return isZip;
    } catch (IOException e) {
        return false;
    }
}
 
Example 22
Source Project: atlas   Source File: ZipUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean removeZipEntry(File file, Pattern pattern, File targetFile)
    throws FileNotFoundException, IOException {
    byte[] buffer = new byte[1024];
    java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetFile)));
    BufferedOutputStream bo = new BufferedOutputStream(out);
    InputStream inputStream;
    Enumeration enumeration = zipFile.entries();
    while (enumeration.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry)enumeration.nextElement();
        String name = zipEntry.getName();
        if (pattern.matcher(name).find()) {
            continue;
        }
        out.putNextEntry(zipEntry);
        inputStream = zipFile.getInputStream(zipEntry);
        write(inputStream, out, buffer);
        bo.flush();

    }

    closeQuitely(zipFile);
    closeQuitely(out);
    closeQuitely(bo);

    return true;
}
 
Example 23
Source Project: atlas   Source File: ZipUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * isZipFile.
 * </p>
 *
 * @param zipFile a {@link File} object.
 * @return a boolean.
 */
public static boolean isZipFile(File zipFile) {
    try {
        ZipFile zf = new ZipFile(zipFile);
        boolean isZip = zf.getEntries().hasMoreElements();
        zf.close();
        return isZip;
    } catch (IOException e) {
        return false;
    }
}
 
Example 24
Source Project: buck   Source File: ZipRuleIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldExcludeEverything() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp);
  workspace.setUp();

  Path zip = workspace.buildAndReturnOutput("//example:excludeall");

  try (ZipFile zipFile = new ZipFile(zip.toFile())) {
    ZipArchiveEntry cake = zipFile.getEntry("cake.txt");
    assertThat(cake, Matchers.nullValue());
    ZipArchiveEntry taco = zipFile.getEntry("menu.txt");
    assertThat(taco, Matchers.nullValue());
  }
}
 
Example 25
Source Project: yes-cart   Source File: ZipUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Unzip archive to given folder.
 *
 * @param archive given archive
 * @param outputDir  given folder
 *
 * @throws IOException in case of error
 */

public void unzipArchive(final File archive, final File outputDir) throws IOException {
    ZipFile zipfile = new ZipFile(archive, encoding);
    for (Enumeration e = zipfile.getEntries(); e.hasMoreElements(); ) {
        final ZipArchiveEntry entry = (ZipArchiveEntry) e.nextElement();
        unzipEntry(zipfile, entry, outputDir);
    }
    zipfile.close();
}
 
Example 26
Source Project: zxpoly   Source File: Spec256Arch.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static byte[] readData(final ZipFile file, final ZipArchiveEntry entry)
    throws IOException {
  final byte[] result = new byte[(int) entry.getSize()];
  final int size = readFully(file.getInputStream(entry), result);
  if (size != result.length) {
    throw new IOException("Wrong read size: " + entry);
  }
  return result;
}
 
Example 27
Source Project: phoenicis   Source File: Zip.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private File unzipEntry(ZipFile zipFile, ZipArchiveEntry entry, Path targetDirectory,
        Consumer<ZipExtractionResult> unzipCallback) {
    final String fileName = entry.getName();
    final long compressedSize = entry.getCompressedSize();

    final Path targetPath = targetDirectory.resolve(fileName);
    try {
        if (entry.isDirectory()) {
            LOGGER.info(String.format("Attempting to create output directory %s.", targetPath.toString()));

            Files.createDirectories(targetPath);
        } else {
            Files.createDirectories(targetPath.getParent());

            try (InputStream in = zipFile.getInputStream(entry)) {
                LOGGER.info(String.format("Creating output file %s.", targetPath.toString()));

                Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);

                // update progress bar
                unzipCallback.accept(new ZipExtractionResult(compressedSize, fileName));
            }
        }

        return targetPath.toFile();
    } catch (IOException e) {
        throw new ArchiveException(String.format("Unable to extract file \"%s\"", fileName), e);
    }
}
 
Example 28
Source Project: buck   Source File: ZipRuleIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldExcludeOnlyCake() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp);
  workspace.setUp();

  Path zip = workspace.buildAndReturnOutput("//example:excludecake");

  try (ZipFile zipFile = new ZipFile(zip.toFile())) {
    ZipArchiveEntry cake = zipFile.getEntry("cake.txt");
    assertThat(cake, Matchers.nullValue());
    ZipArchiveEntry taco = zipFile.getEntry("menu.txt");
    assertThat(taco, Matchers.notNullValue());
  }
}
 
Example 29
Source Project: kylin   Source File: ZipFileUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void decompressZipfileToDirectory(String zipFileName, File outputFolder)
        throws IOException, ArchiveException {
    if (!validateZipFilename(zipFileName)) {
        throw new RuntimeException("Zip file must end with .zip");
    }
    Expander expander = new Expander();
    ZipFile zipFile = new ZipFile(zipFileName);
    expander.expand(zipFile, outputFolder);
}
 
Example 30
Source Project: james-project   Source File: ZipAssertTest.java    License: Apache License 2.0 5 votes vote down vote up
@SafeVarargs
private ZipFile buildZipFile(SimpleImmutableEntry<String, byte[]>... entries) throws Exception {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {
        for (SimpleImmutableEntry<String, byte[]> entry : entries) {
            ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new File("any"), entry.getKey());
            archiveOutputStream.putArchiveEntry(archiveEntry);
            IOUtils.copy(new ByteArrayInputStream(entry.getValue()), archiveOutputStream);
            archiveOutputStream.closeArchiveEntry();
        }
        archiveOutputStream.finish();
    }

    return new ZipFile(destination);
}