Example usage for java.util.zip ZipEntry STORED

List of usage examples for java.util.zip ZipEntry STORED

Introduction

In this page you can find the example usage for java.util.zip ZipEntry STORED.

Prototype

int STORED

To view the source code for java.util.zip ZipEntry STORED.

Click Source Link

Document

Compression method for uncompressed entries.

Usage

From source file:com.yifanlu.PSXperiaTool.ZpakCreate.java

public void create(boolean noCompress) throws IOException {
    Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(),
            !noCompress);//ww w  . j a v  a2s  .  c  o  m
    IOFileFilter filter = new IOFileFilter() {
        public boolean accept(File file) {
            if (file.getName().startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }

        public boolean accept(File file, String s) {
            if (s.startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }
    };
    Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE);
    ZipOutputStream out = new ZipOutputStream(mOut);
    out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED);
    while (it.hasNext()) {
        File current = it.next();
        FileInputStream in = new FileInputStream(current);
        ZipEntry zEntry = new ZipEntry(
                current.getPath().replace(mDirectory.getPath(), "").substring(1).replace("\\", "/"));
        if (noCompress) {
            zEntry.setSize(in.getChannel().size());
            zEntry.setCompressedSize(in.getChannel().size());
            zEntry.setCrc(getCRC32(current));
        }
        out.putNextEntry(zEntry);
        Logger.verbose("Adding file %s", current.getPath());
        int n;
        while ((n = in.read(mBuffer)) != -1) {
            out.write(mBuffer, 0, n);
        }
        in.close();
        out.closeEntry();
    }
    out.close();
    Logger.debug("Done with ZPAK creation.");
}

From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessUtils.java

/**
 * Adds the given file to the given zip output stream using the given name as the zip entry name. This method will
 * NOT call finish on the zip output stream at the end.
 * //from  w  w  w.ja  v a  2  s. c  o m
 * @param zos the zip output stream to add the file to. This stream must already be open.
 * @param file the file to put in the zip.
 * @param name the name to use for this zip entry.
 * @param addAsStored if true, then the file will be added to the zip as a STORED entry (e.g. without applying
 *            compression to it); if false, then the file will be added to the zip as a DEFLATED entry.
 * @throws IOException if there is an error writing to the stream
 */
public void writeZipEntry(ZipOutputStream zos, File file, String name, boolean addAsStored) throws IOException {
    final ZipEntry ze = new ZipEntry(name);
    ze.setMethod(addAsStored ? ZipEntry.STORED : ZipEntry.DEFLATED);
    if (addAsStored) {
        ze.setSize(file.length());
        ze.setCrc(FileUtils.checksumCRC32(file));
    }
    zos.putNextEntry(ze);
    final InputStream is = FileUtils.openInputStream(file);
    IOUtils.copy(is, zos);
    zos.closeEntry();
    zos.flush();
    IOUtils.closeQuietly(is);
}

From source file:eionet.gdem.utils.ZipUtil.java

/**
 *
 * @param f//w w w  . jav  a2  s.  c  o  m
 *            - File that will be zipped
 * @param outZip
 *            - ZipOutputStream represents the zip file, where the files will be placed
 * @param sourceDir
 *            - root directory, where the zipping started
 * @param doCompress
 *            - don't comress the file, if doCompress=true
 * @throws IOException If an error occurs.
 */
public static void zipFile(File f, ZipOutputStream outZip, String sourceDir, boolean doCompress)
        throws IOException {

    // Read the source file into byte array
    byte[] fileBytes = Utils.getBytesFromFile(f);

    // create a new zip entry
    String strAbsPath = f.getPath();
    String strZipEntryName = strAbsPath.substring(sourceDir.length() + 1, strAbsPath.length());
    strZipEntryName = Utils.Replace(strZipEntryName, File.separator, "/");
    ZipEntry anEntry = new ZipEntry(strZipEntryName);

    // Don't compress the file, if not needed
    if (!doCompress) {
        // ZipEntry can't calculate crc size automatically, if we use STORED method.
        anEntry.setMethod(ZipEntry.STORED);
        anEntry.setSize(fileBytes.length);
        CRC32 crc321 = new CRC32();
        crc321.update(fileBytes);
        anEntry.setCrc(crc321.getValue());
    }
    // place the zip entry in the ZipOutputStream object
    outZip.putNextEntry(anEntry);

    // now write the content of the file to the ZipOutputStream
    outZip.write(fileBytes);

    outZip.flush();
    // Close the current entry
    outZip.closeEntry();

}

From source file:com.facebook.buck.zip.UnzipTest.java

@Test
public void testExtractZipFilePreservesExecutePermissionsAndModificationTime() throws IOException {

    // getFakeTime returs time with some non-zero millis. By doing division and multiplication by
    // 1000 we get rid of that.
    final long time = ZipConstants.getFakeTime() / 1000 * 1000;

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("test.exe");
        entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------")));
        entry.setSize(DUMMY_FILE_CONTENTS.length);
        entry.setMethod(ZipEntry.STORED);
        entry.setTime(time);//from  w w  w . j ava  2s. c  o m
        zip.putArchiveEntry(entry);
        zip.write(DUMMY_FILE_CONTENTS);
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            Unzip.ExistingFileMode.OVERWRITE);
    Path exe = extractFolder.toAbsolutePath().resolve("test.exe");
    assertTrue(Files.exists(exe));
    assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time));
    assertTrue(Files.isExecutable(exe));
    assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result);
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractZipFilePreservesExecutePermissionsAndModificationTime()
        throws InterruptedException, IOException {

    // getFakeTime returs time with some non-zero millis. By doing division and multiplication by
    // 1000 we get rid of that.
    long time = ZipConstants.getFakeTime() / 1000 * 1000;

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("test.exe");
        entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------")));
        entry.setSize(DUMMY_FILE_CONTENTS.length);
        entry.setMethod(ZipEntry.STORED);
        entry.setTime(time);//from ww  w  .ja v a 2s  .co  m
        zip.putArchiveEntry(entry);
        zip.write(DUMMY_FILE_CONTENTS);
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(
            new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE);
    Path exe = extractFolder.toAbsolutePath().resolve("test.exe");
    assertTrue(Files.exists(exe));
    assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time));
    assertTrue(Files.isExecutable(exe));
    assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result);
}

From source file:com.facebook.buck.zip.UnzipTest.java

@Test
public void testExtractSymlink() throws IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MoreFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);
        zip.putArchiveEntry(entry);/*w  w w.  j a  v  a  2  s  .  c  o m*/
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            Unzip.ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractSymlink() throws InterruptedException, IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MostFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);
        zip.putArchiveEntry(entry);// www  . ja v a  2  s  . com
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractBrokenSymlinkWithOwnerExecutePermissions() throws InterruptedException, IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MostFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);

        // Mark the file as being executable.
        Set<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE);

        long externalAttributes = entry.getExternalAttributes()
                + (MorePosixFilePermissions.toMode(filePermissions) << 16);
        entry.setExternalAttributes(externalAttributes);

        zip.putArchiveEntry(entry);//w  ww. ja  v a2  s .  c o m
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

From source file:com.facebook.buck.zip.ZipStepTest.java

@Test
public void zipWithEmptyDir() throws IOException {
    Path parent = tmp.newFolder("zipstep");
    Path out = parent.resolve("output.zip");

    tmp.newFolder("zipdir");
    tmp.newFolder("zipdir/foo/");
    tmp.newFolder("zipdir/bar/");

    ZipStep step = new ZipStep(filesystem, Paths.get("zipstep/output.zip"), ImmutableSet.of(), true,
            ZipCompressionLevel.DEFAULT_COMPRESSION_LEVEL, Paths.get("zipdir"));
    assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());

    try (Zip zip = new Zip(out, false)) {
        assertEquals(ImmutableSet.of("", "foo/", "bar/"), zip.getDirNames());
    }/*www .j a  v a2  s  .  co m*/

    // Directories should be stored, not deflated as this sometimes causes issues
    // (e.g. installing an .ipa over the air in iOS 9.1)
    try (ZipInputStream is = new ZipInputStream(new FileInputStream(out.toFile()))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertEquals(entry.getName(), ZipEntry.STORED, entry.getMethod());
        }
    }
}

From source file:io.fabric8.maven.generator.springboot.SpringBootGenerator.java

private ZipEntry createZipEntry(File file, String fullPath) throws IOException {
    ZipEntry entry = new ZipEntry(fullPath);

    byte[] buffer = new byte[8192];
    int bytesRead = -1;
    try (InputStream is = new FileInputStream(file)) {
        CRC32 crc = new CRC32();
        int size = 0;
        while ((bytesRead = is.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
            size += bytesRead;/*  w  ww.  j a va  2  s.  c  o m*/
        }
        entry.setSize(size);
        entry.setCompressedSize(size);
        entry.setCrc(crc.getValue());
        entry.setMethod(ZipEntry.STORED);
        return entry;
    }
}