Example usage for java.util.zip ZipOutputStream write

List of usage examples for java.util.zip ZipOutputStream write

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream write.

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:org.cloudfoundry.client.lib.io.DynamicZipInputStreamTest.java

@Test
public void shouldCreateValidZipContent() throws Exception {

    byte[] f1 = newRandomBytes(10000);
    byte[] f2 = newRandomBytes(10000);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(bos);
    zipOutputStream.putNextEntry(new ZipEntry("a/b/c"));
    zipOutputStream.write(f1);
    zipOutputStream.closeEntry();//ww w . ja  v  a 2  s.  c  om
    zipOutputStream.putNextEntry(new ZipEntry("a/b/c/d/"));
    zipOutputStream.closeEntry();
    zipOutputStream.putNextEntry(new ZipEntry("d/e/f"));
    zipOutputStream.write(f2);
    zipOutputStream.closeEntry();
    zipOutputStream.flush();
    zipOutputStream.close();
    byte[] expected = bos.toByteArray();

    List<DynamicZipInputStream.Entry> entries = new ArrayList<DynamicZipInputStream.Entry>();
    entries.add(newEntry("a/b/c", f1));
    entries.add(newEntry("a/b/c/d/", null));
    entries.add(newEntry("d/e/f", f2));
    DynamicZipInputStream inputStream = new DynamicZipInputStream(entries);
    bos.reset();
    FileCopyUtils.copy(inputStream, bos);
    byte[] actual = bos.toByteArray();

    assertThat(actual, is(equalTo(expected)));
}

From source file:org.apache.hadoop.streaming.TestMultipleArchiveFiles.java

protected void createInput() throws IOException {
    fileSys.delete(new Path(INPUT_DIR), true);
    DataOutputStream dos = fileSys.create(new Path(INPUT_FILE));
    String inputFileString = "symlink1" + File.separator + "cacheArchive1\nsymlink2" + File.separator
            + "cacheArchive2";
    dos.write(inputFileString.getBytes("UTF-8"));
    dos.close();//from  w w  w  . jav  a2  s  . com

    DataOutputStream out = fileSys.create(new Path(CACHE_ARCHIVE_1.toString()));
    ZipOutputStream zos = new ZipOutputStream(out);
    ZipEntry ze = new ZipEntry(CACHE_FILE_1.toString());
    zos.putNextEntry(ze);
    zos.write(input.getBytes("UTF-8"));
    zos.closeEntry();
    zos.close();

    out = fileSys.create(new Path(CACHE_ARCHIVE_2.toString()));
    zos = new ZipOutputStream(out);
    ze = new ZipEntry(CACHE_FILE_2.toString());
    zos.putNextEntry(ze);
    zos.write(input.getBytes("UTF-8"));
    zos.closeEntry();
    zos.close();
}

From source file:org.agnitas.util.ZipUtilities.java

/**
 * Add data to an open ZipOutputStream as a virtual file
 * /*from www.j  a v a2s  .  c om*/
 * @param fileData
 * @param relativeDirPath
 * @param filename
 * @param destinationZipFileSream
 * @throws IOException
 */
public static void addFileDataToOpenZipFileStream(byte[] fileData, String relativeDirPath, String filename,
        ZipOutputStream destinationZipFileSream) throws IOException {
    if (fileData == null)
        throw new IOException("FileData is missing");

    if (StringUtils.isEmpty(filename) || filename.trim().length() == 0)
        throw new IOException("Filename is missing");

    if (destinationZipFileSream == null)
        throw new IOException("DestinationStream is not ready");

    if (relativeDirPath == null || (!relativeDirPath.endsWith("/") && !relativeDirPath.endsWith("\\")))
        throw new IOException("RelativeDirPath is invalid");

    ZipEntry entry = new ZipEntry(relativeDirPath + filename);
    entry.setTime(new Date().getTime());
    destinationZipFileSream.putNextEntry(entry);

    destinationZipFileSream.write(fileData);

    destinationZipFileSream.flush();
    destinationZipFileSream.closeEntry();
}

From source file:ZipUtilInPlaceTest.java

public void testByteArrayTransformer() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file1 = File.createTempFile("temp", null);
    try {//  www .j  a  va  2  s  .co  m
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        ZipUtil.transformEntry(file1, name, new ByteArrayZipEntryTransformer() {
            protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException {
                String s = new String(input);
                assertEquals(new String(contents), s);
                return s.toUpperCase().getBytes();
            }
        });

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file1, name);
        assertNotNull(actual);
        assertEquals(new String(contents).toUpperCase(), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
    }
}

From source file:eu.europa.ejusticeportal.dss.controller.action.DownloadSignedPdf.java

/**
 * @param sf/*from   ww w  .j av a2 s .c om*/
 * @param response
 * @throws IOException 
 */
private void writeZip(SignedForm sf, HttpServletResponse response, String fileName) throws IOException {
    ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
    ZipEntry ze = new ZipEntry(fileName);
    zos.putNextEntry(ze);
    zos.write(sf.getDocument());
    ze = new ZipEntry(fileName + ".xml");
    zos.putNextEntry(ze);
    zos.write(sf.getDetachedSignature());
    zos.closeEntry();
    zos.close();
}

From source file:com.xpn.xwiki.plugin.packaging.AbstractPackageTest.java

/**
 * Create a XAR file using java.util.zip.
 *
 * @param docs The documents to include.
 * @param encodings The charset for each document.
 * @param packageXmlEncoding The encoding of package.xml
 * @return the XAR file as a byte array.
 *//*from   ww w.  j a v a  2  s . co  m*/
protected byte[] createZipFile(XWikiDocument docs[], String[] encodings, String packageXmlEncoding)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry zipp = new ZipEntry("package.xml");
    zos.putNextEntry(zipp);
    zos.write(getEncodedByteArray(getPackageXML(docs, packageXmlEncoding), packageXmlEncoding));
    for (int i = 0; i < docs.length; i++) {
        String zipEntryName = docs[i].getSpace() + "/" + docs[i].getName();
        if (docs[i].getTranslation() != 0) {
            zipEntryName += "." + docs[i].getLanguage();
        }
        ZipEntry zipe = new ZipEntry(zipEntryName);
        zos.putNextEntry(zipe);
        String xmlCode = docs[i].toXML(false, false, false, false, getContext());
        zos.write(getEncodedByteArray(xmlCode, encodings[i]));
    }
    zos.finish();
    zos.close();
    return baos.toByteArray();
}

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

/**
 *
 * @param f/*from w w w .  ja va 2 s  . c om*/
 *            - 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:b2s.idea.mavenize.JarCombiner.java

private void addServiceEntries(ZipOutputStream zipOut, JarContext context) throws IOException {
    for (Map.Entry<String, StringBuilder> entry : context.getServices()) {
        zipOut.putNextEntry(new ZipEntry(entry.getKey()));
        zipOut.write(entry.getValue().toString().getBytes());
        zipOut.closeEntry();/*from w  w  w. j  av  a  2 s.com*/
    }
}

From source file:org.codehaus.cargo.module.JarArchiveTest.java

/**
 * Verifies that the method <code>expandToPath()</code> works.
 * /*  w w  w.  j  a va  2 s.  c o m*/
 * @throws Exception If an unexpected error occurs
 */
public void testExpandToPath() throws Exception {
    FileObject testJar = this.fsManager.resolveFile("ram:///test.jar");
    ZipOutputStream zos = new ZipOutputStream(testJar.getContent().getOutputStream());
    ZipEntry zipEntry = new ZipEntry("rootResource.txt");
    zos.putNextEntry(zipEntry);
    zos.write("Some content".getBytes("UTF-8"));
    zos.closeEntry();
    zos.close();

    DefaultJarArchive jarArchive = new DefaultJarArchive("ram:///test.jar");
    jarArchive.setFileHandler(new VFSFileHandler(this.fsManager));

    jarArchive.expandToPath("ram:///test");

    // Verify that the rootResource.txt file has been correctly expanded
    assertTrue(this.fsManager.resolveFile("ram:///test/rootResource.txt").exists());
}

From source file:org.fenixedu.start.controller.StartController.java

private ResponseEntity<byte[]> build(Map<String, byte[]> project, ProjectRequest request) throws IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(stream);

    for (Map.Entry<String, byte[]> mapEntry : project.entrySet()) {
        ZipEntry entry = new ZipEntry(request.getArtifactId() + "/" + mapEntry.getKey());
        zip.putNextEntry(entry);//  w  w w.ja  va2 s . co  m
        zip.write(mapEntry.getValue());
        zip.closeEntry();
    }

    zip.close();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/zip");
    headers.add("Content-Disposition", "attachment; filename=\"" + request.getArtifactId() + ".zip\"");
    return new ResponseEntity<>(stream.toByteArray(), headers, HttpStatus.OK);
}