Java Code Examples for java.util.zip.ZipEntry#setTime()

The following examples show how to use java.util.zip.ZipEntry#setTime() . 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 File: ZipFactory.java    From bazel with Apache License 2.0 6 votes vote down vote up
public byte[] toByteArray() {
  try {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zipper = new ZipOutputStream(out);
    for (Entry entry : entries) {
      ZipEntry zipEntry = new ZipEntry(entry.name);
      if (entry.compressed) {
        zipEntry.setMethod(ZipEntry.DEFLATED);
      } else {
        zipEntry.setMethod(ZipEntry.STORED);
        zipEntry.setSize(entry.content.length);
        zipEntry.setCrc(calculateCrc32(entry.content));
      }
      zipEntry.setTime(ZipCombiner.DOS_EPOCH.getTime());
      zipper.putNextEntry(zipEntry);
      zipper.write(entry.content);
      zipper.closeEntry();
    }
    zipper.close();
    return out.toByteArray();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 2
Source File: ZipUtils.java    From litchi with Apache License 2.0 6 votes vote down vote up
/**
 * 压缩文件
 *
 */
private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
	if (!file.exists()) {
		return;
	}
	try {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		ZipEntry entry = new ZipEntry(baseDir + file.getName());
		entry.setTime(file.lastModified());
		zos.putNextEntry(entry);
		int count;
		byte[] buf = new byte[8192];
		while ((count = bis.read(buf)) != -1) {
			zos.write(buf, 0, count);
		}
		bis.close();
	} catch (Exception e) {
		LOGGER.error("", e);
	}
}
 
Example 3
Source File: ZipOutputStreamTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToAddASingleNonZeroLengthFile() throws IOException {
  File reference = File.createTempFile("reference", ".zip");

  try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output, mode);
      ZipOutputStream ref = new ZipOutputStream(new FileOutputStream(reference))) {
    byte[] bytes = "cheese".getBytes();
    ZipEntry entry = new ZipEntry("example.txt");
    entry.setTime(System.currentTimeMillis());
    out.putNextEntry(entry);
    ref.putNextEntry(entry);
    out.write(bytes);
    ref.write(bytes);
  }

  byte[] seen = Files.readAllBytes(output);
  byte[] expected = Files.readAllBytes(reference.toPath());

  assertArrayEquals(expected, seen);
}
 
Example 4
Source File: TestExtraTime.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static void testTimeConversions(long from, long to, long step) {
    ZipEntry ze = new ZipEntry("TestExtraTime.java");
    for (long time = from; time <= to; time += step) {
        ze.setTime(time);
        FileTime lastModifiedTime = ze.getLastModifiedTime();
        if (lastModifiedTime.toMillis() != time) {
            throw new RuntimeException("setTime should make getLastModifiedTime " +
                    "return the specified instant: " + time +
                    " got: " + lastModifiedTime.toMillis());
        }
        if (ze.getTime() != time) {
            throw new RuntimeException("getTime after setTime, expected: " +
                    time + " got: " + ze.getTime());
        }
    }
}
 
Example 5
Source File: ZipReaderTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test public void testZipEntryInvalidTime() throws IOException {
  long date = 312796800000L; // 11/30/1979 00:00:00, which is also 0 in DOS format
  byte[] extra = new ExtraData((short) 0xaa, new byte[] { (byte) 0xbb, (byte) 0xcd }).getBytes();
  try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(test))) {
    ZipEntry foo = new ZipEntry("foo");
    foo.setComment("foo comment.");
    foo.setMethod(ZipEntry.DEFLATED);
    foo.setTime(date);
    foo.setExtra(extra);
    zout.putNextEntry(foo);
    zout.write("foo".getBytes(UTF_8));
    zout.closeEntry();
  }

  try (ZipReader reader = new ZipReader(test, UTF_8)) {
    ZipFileEntry fooEntry = reader.getEntry("foo");
    assertThat(fooEntry.getTime()).isEqualTo(ZipUtil.DOS_EPOCH);
  }
}
 
Example 6
Source File: ZipEntryTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void checkSetTime(long time) throws IOException {
  File f = createTemporaryZipFile();
  ZipOutputStream out = createZipOutputStream(f);
  ZipEntry ze = new ZipEntry("x");
  ze.setSize(0);
  ze.setTime(time);
  out.putNextEntry(ze);
  out.closeEntry();
  out.close();

  // Read it back, and check that we see the entry.
  ZipFile zipFile = new ZipFile(f);
  assertEquals(time, zipFile.getEntry("x").getTime());
  zipFile.close();
}
 
Example 7
Source File: DatabaseClassLoadingTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void addFile(ZipOutputStream zos, File f, String dbName, int old)
        throws IOException {

    String s = f.getPath().replace(File.separatorChar, '/');

    s = s.substring(old);

    s = dbName.concat(s);

    // jar has forward slashes!
    ZipEntry ze = new ZipEntry(s);
    ze.setTime(f.lastModified());

    zos.putNextEntry(ze);

    byte[] buf = new byte[4096];
    BufferedInputStream in = new BufferedInputStream(
            (new FileInputStream(f)));
    while (true) {
        int read = in.read(buf);
        if (read == -1) {
            break;
        }
        zos.write(buf, 0, read);
    }

    in.close();
    zos.closeEntry();
}
 
Example 8
Source File: dbjarUtil.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
static void addFile(
      ZipOutputStream zos, 
      File f, String dbName, int old) throws IOException
  {

String s = f.getPath().replace(File.separatorChar, '/');

s = s.substring(old);

s = dbName.concat(s);

// jar has forward slashes!
      ZipEntry ze= new ZipEntry(s); 
      ze.setTime(f.lastModified()); 

      zos.putNextEntry(ze); 

byte[] byte8= new byte[1024]; 
      BufferedInputStream bufferedInputStream10= new BufferedInputStream((new FileInputStream(f))); 
      while (true)
      {
          int int9= bufferedInputStream10.read(byte8, 0, byte8.length); 
          if (int9 == -1)
          {
              break;
          }
          zos.write(byte8, 0, int9); 
      }

      bufferedInputStream10.close(); 
      zos.closeEntry(); 
  }
 
Example 9
Source File: RejarClassesForAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ZipEntry newZipEntry(ZipEntry ze) {
    ZipEntry ze2 = new ZipEntry(ze.getName());
    ze2.setComment(ze.getComment());
    ze2.setTime(ze.getTime());
    ze2.setExtra(ze.getExtra());
    return ze2;
}
 
Example 10
Source File: ZipOutputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test standard and info-zip-extended timestamp rounding
 */
public void test_timeSerializationRounding() throws Exception {
    List<ZipEntry> entries = new ArrayList<>();
    ZipEntry zipEntry;

    entries.add(zipEntry = new ZipEntry("test1"));
    final long someTimestamp = 1479139143200L;
    zipEntry.setTime(someTimestamp);

    entries.add(zipEntry = new ZipEntry("test2"));
    zipEntry.setLastModifiedTime(FileTime.fromMillis(someTimestamp));

    for (ZipEntry entry : entries) {
        zos.putNextEntry(entry);
        zos.write(data.getBytes());
        zos.closeEntry();
    }
    zos.close();

    try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()))) {
       // getTime should be rounded down to a multiple of 2s
        ZipEntry readEntry = zis.getNextEntry();
        assertEquals((someTimestamp / 2000) * 2000,
                     readEntry.getTime());

        // With extended timestamp getTime&getLastModifiedTime should berounded down to a
        // multiple of 1s
        readEntry = zis.getNextEntry();
        assertEquals((someTimestamp / 1000) * 1000,
                     readEntry.getLastModifiedTime().toMillis());
        assertEquals((someTimestamp / 1000) * 1000,
                     readEntry.getTime());
    }
}
 
Example 11
Source File: ZipFiles.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * Private helper function for zipping files. This one goes recursively through the input
 * directory and all of its subdirectories and adds the single zip entries.
 *
 * @param inputFile the file or directory to be added to the zip file
 * @param directoryName the string-representation of the parent directory name. Might be an empty
 *     name, or a name containing multiple directory names separated by "/". The directory name
 *     must be a valid name according to the file system limitations. The directory name should be
 *     empty or should end in "/".
 * @param zos the zipstream to write to
 * @throws IOException the zipping failed, e.g. because the output was not writeable.
 */
private static void zipDirectoryInternal(
    File inputFile, String directoryName, ZipOutputStream zos) throws IOException {
  String entryName = directoryName + inputFile.getName();
  if (inputFile.isDirectory()) {
    entryName += "/";

    // We are hitting a sub-directory. Recursively add children to zip in deterministic,
    // sorted order.
    File[] childFiles = inputFile.listFiles();
    if (childFiles.length > 0) {
      Arrays.sort(childFiles);
      // loop through the directory content, and zip the files
      for (File file : childFiles) {
        zipDirectoryInternal(file, entryName, zos);
      }

      // Since this directory has children, exit now without creating a zipentry specific to
      // this directory. The entry for a non-entry directory is incompatible with certain
      // implementations of unzip.
      return;
    }
  }

  // Put the zip-entry for this file or empty directory into the zipoutputstream.
  ZipEntry entry = new ZipEntry(entryName);
  entry.setTime(inputFile.lastModified());
  zos.putNextEntry(entry);

  // Copy file contents into zipoutput stream.
  if (inputFile.isFile()) {
    Files.asByteSource(inputFile).copyTo(zos);
  }
}
 
Example 12
Source File: NativeUnpack.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}
 
Example 13
Source File: PlatformProviderGenerator.java    From flogger with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
  // Create the class.
  ClassWriter classWriter = new ClassWriter(0);
  classWriter.visit(
      V1_6,
      ACC_PUBLIC + ACC_FINAL + ACC_SUPER,
      "com/google/common/flogger/backend/PlatformProvider",
      null,
      "java/lang/Object",
      null);

  // Create the no-op constructor.
  MethodVisitor methodVisitor = classWriter.visitMethod(ACC_PRIVATE, "<init>", "()V", null, null);
  methodVisitor.visitCode();
  methodVisitor.visitVarInsn(ALOAD, 0);
  methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
  methodVisitor.visitInsn(RETURN);
  methodVisitor.visitMaxs(1, 1);
  methodVisitor.visitEnd();

  // Create the static getter method.
  methodVisitor =
      classWriter.visitMethod(
          ACC_PUBLIC + ACC_STATIC,
          "getPlatform",
          "()Lcom/google/common/flogger/backend/Platform;",
          null,
          null);
  // Try the different platforms.
  for (String platformClass : PLATFORM_CLASSES) {
    tryBlockForPlatform(methodVisitor, platformClass);
  }
  // Return null if no platform is found.
  methodVisitor.visitInsn(ACONST_NULL);
  methodVisitor.visitInsn(ARETURN);
  methodVisitor.visitMaxs(2, 1);
  methodVisitor.visitEnd();

  // Finish creating the class.
  classWriter.visitEnd();

  // Write the class to the output file.
  Path path = Paths.get(args[0]);
  Files.createDirectories(path.getParent());
  try (JarOutputStream jar =
      new JarOutputStream(Files.newOutputStream(path, StandardOpenOption.CREATE_NEW))) {
    ZipEntry entry = new ZipEntry("com/google/common/flogger/backend/PlatformProvider.class");
    entry.setTime(0); // clear timestamp to ensure JAR is deterministic for cache during builds.
    jar.putNextEntry(entry);
    jar.write(classWriter.toByteArray());
    jar.closeEntry();
  }
}
 
Example 14
Source File: TestWorldDirectoryWriter.java    From amidst with GNU General Public License v3.0 4 votes vote down vote up
private ZipEntry createZipEntry(String name) {
	ZipEntry result = new ZipEntry(name + JSON_FILE_EXTENSION);
	result.setTime(0);
	return result;
}
 
Example 15
Source File: NativeUnpack.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}
 
Example 16
Source File: NativeUnpack.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}
 
Example 17
Source File: ArchiveBuilder.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public void addFile(String path, File file) throws IOException {
	if (!file.isFile()) {
		throw new AssertException("Attempted to write a directory to the jar file");
	}

	long modifiedTime = file.lastModified();

	ZipEntry entry = new ZipEntry(path);
	entry.setTime(modifiedTime);

	zipOut.putNextEntry(entry);

	InputStream in = new FileInputStream(file);

	byte[] bytes = new byte[4096];
	int numRead;

	while ((numRead = in.read(bytes)) != -1) {
		zipOut.write(bytes, 0, numRead);
	}
	in.close();

	zipOut.closeEntry();

}
 
Example 18
Source File: NativeUnpack.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void writeEntry(JarOutputStream j, String name,
                        long mtime, long lsize, boolean deflateHint,
                        ByteBuffer data0, ByteBuffer data1) throws IOException {
    int size = (int)lsize;
    if (size != lsize)
        throw new IOException("file too large: "+lsize);

    CRC32 crc32 = _crc32;

    if (_verbose > 1)
        Utils.log.fine("Writing entry: "+name+" size="+size
                         +(deflateHint?" deflated":""));

    if (_buf.length < size) {
        int newSize = size;
        while (newSize < _buf.length) {
            newSize <<= 1;
            if (newSize <= 0) {
                newSize = size;
                break;
            }
        }
        _buf = new byte[newSize];
    }
    assert(_buf.length >= size);

    int fillp = 0;
    if (data0 != null) {
        int size0 = data0.capacity();
        data0.get(_buf, fillp, size0);
        fillp += size0;
    }
    if (data1 != null) {
        int size1 = data1.capacity();
        data1.get(_buf, fillp, size1);
        fillp += size1;
    }
    while (fillp < size) {
        // Fill in rest of data from the stream itself.
        int nr = in.read(_buf, fillp, size - fillp);
        if (nr <= 0)  throw new IOException("EOF at end of archive");
        fillp += nr;
    }

    ZipEntry z = new ZipEntry(name);
    z.setTime(mtime * 1000);

    if (size == 0) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(0);
        z.setCrc(0);
        z.setCompressedSize(0);
    } else if (!deflateHint) {
        z.setMethod(ZipOutputStream.STORED);
        z.setSize(size);
        z.setCompressedSize(size);
        crc32.reset();
        crc32.update(_buf, 0, size);
        z.setCrc(crc32.getValue());
    } else {
        z.setMethod(Deflater.DEFLATED);
        z.setSize(size);
    }

    j.putNextEntry(z);

    if (size > 0)
        j.write(_buf, 0, size);

    j.closeEntry();
    if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
}
 
Example 19
Source File: ZipReaderTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Test public void testZipEntryFields() throws IOException {
  CRC32 crc = new CRC32();
  Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
  long date = 791784306000L; // 2/3/1995 04:05:06
  byte[] extra = new ExtraData((short) 0xaa, new byte[] { (byte) 0xbb, (byte) 0xcd }).getBytes();
  byte[] tmp = new byte[128];
  try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(test))) {

    ZipEntry foo = new ZipEntry("foo");
    foo.setComment("foo comment.");
    foo.setMethod(ZipEntry.DEFLATED);
    foo.setTime(date);
    foo.setExtra(extra);
    zout.putNextEntry(foo);
    zout.write("foo".getBytes(UTF_8));
    zout.closeEntry();

    ZipEntry bar = new ZipEntry("bar");
    bar.setComment("bar comment.");
    bar.setMethod(ZipEntry.STORED);
    bar.setSize("bar".length());
    bar.setCompressedSize("bar".length());
    crc.reset();
    crc.update("bar".getBytes(UTF_8));
    bar.setCrc(crc.getValue());
    zout.putNextEntry(bar);
    zout.write("bar".getBytes(UTF_8));
    zout.closeEntry();
  }

  try (ZipReader reader = new ZipReader(test, UTF_8)) {
    ZipFileEntry fooEntry = reader.getEntry("foo");
    assertThat(fooEntry.getName()).isEqualTo("foo");
    assertThat(fooEntry.getComment()).isEqualTo("foo comment.");
    assertThat(fooEntry.getMethod()).isEqualTo(Compression.DEFLATED);
    assertThat(fooEntry.getVersion()).isEqualTo(Compression.DEFLATED.getMinVersion());
    assertThat(fooEntry.getTime()).isEqualTo(date);
    assertThat(fooEntry.getSize()).isEqualTo("foo".length());
    deflater.reset();
    deflater.setInput("foo".getBytes(UTF_8));
    deflater.finish();
    assertThat(fooEntry.getCompressedSize()).isEqualTo(deflater.deflate(tmp));
    crc.reset();
    crc.update("foo".getBytes(UTF_8));
    assertThat(fooEntry.getCrc()).isEqualTo(crc.getValue());
    assertThat(fooEntry.getExtra().getBytes()).isEqualTo(extra);

    ZipFileEntry barEntry = reader.getEntry("bar");
    assertThat(barEntry.getName()).isEqualTo("bar");
    assertThat(barEntry.getComment()).isEqualTo("bar comment.");
    assertThat(barEntry.getMethod()).isEqualTo(Compression.STORED);
    assertThat(barEntry.getVersion()).isEqualTo(Compression.STORED.getMinVersion());
    assertDateAboutNow(new Date(barEntry.getTime()));
    assertThat(barEntry.getSize()).isEqualTo("bar".length());
    assertThat(barEntry.getCompressedSize()).isEqualTo("bar".length());
    crc.reset();
    crc.update("bar".getBytes(UTF_8));
    assertThat(barEntry.getCrc()).isEqualTo(crc.getValue());
    assertThat(barEntry.getExtra().getBytes()).isEqualTo(new byte[] {});
  }
}
 
Example 20
Source File: ZipUtilities.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Compress a file or recursively compress all files of a folder.
 * 
 * @param sourceFile
 * @param destinationZipFileSream
 * @throws IOException
 */
public static void addFileToOpenZipFileStream(final File sourceFile, final String relativeDirPath, final ZipOutputStream destinationZipFileSream) throws IOException {
	if (!sourceFile.exists()) {
		throw new IOException("SourceFile does not exist");
	}
		
	if (destinationZipFileSream == null) {
		throw new IOException("DestinationStream is not ready");
	}
	
	if (relativeDirPath == null) {
		throw new IOException("RelativeDirPath is invalid");
	}
	
	try {
		if (!sourceFile.isDirectory()) {
			final ZipEntry entry = new ZipEntry(relativeDirPath + sourceFile.getName());
			entry.setTime(sourceFile.lastModified());
			destinationZipFileSream.putNextEntry(entry);
			
			try(final BufferedInputStream bufferedFileInputStream = new BufferedInputStream(new FileInputStream(sourceFile))) {
				final byte[] bufferArray = new byte[1024];
				int byteBufferFillLength = bufferedFileInputStream.read(bufferArray);
				while (byteBufferFillLength > -1) {
					destinationZipFileSream.write(bufferArray, 0, byteBufferFillLength);
					byteBufferFillLength = bufferedFileInputStream.read(bufferArray);
				}
				destinationZipFileSream.flush();
				destinationZipFileSream.closeEntry();
			}
		}
		else {
			for (File sourceSubFile : sourceFile.listFiles()) {
				addFileToOpenZipFileStream(sourceSubFile, relativeDirPath + sourceFile.getName() + File.separator, destinationZipFileSream);
			}
		}
	}
	catch (IOException e) {
		throw e;
	}
}