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 synchronized void write(byte[] b, int off, int len) throws IOException 

Source Link

Document

Writes an array of bytes to the current ZIP entry data.

Usage

From source file:org.apache.chemistry.opencmis.tools.specexamples.SpecExamples.java

private static void addDirectory(ZipOutputStream zout, String prefix, File sourceDir) throws IOException {

    File[] files = sourceDir.listFiles();
    LOG.debug("Create Zip, adding directory " + sourceDir.getName());

    if (null != files) {
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                addDirectory(zout, prefix + File.separator + files[i].getName(), files[i]);
            } else {
                LOG.debug("Create Zip, adding file {}", files[i].getName());
                byte[] buffer = new byte[BUFSIZE];
                FileInputStream fin = new FileInputStream(files[i]);
                try {
                    String zipEntryName = prefix + File.separator + files[i].getName();
                    LOG.debug("   adding entry " + zipEntryName);
                    zout.putNextEntry(new ZipEntry(zipEntryName));

                    int length;
                    while ((length = fin.read(buffer)) > 0) {
                        zout.write(buffer, 0, length);
                    }/*from   w  ww . j  a  v  a  2s  .  co m*/
                } finally {
                    IOUtils.closeQuietly(fin);
                    try {
                        zout.closeEntry();
                    } catch (IOException ioe) {
                        LOG.debug("Closing zip entry failed: {}", ioe.toString(), ioe);
                    }
                }
            }
        }
    }
}

From source file:org.egov.wtms.web.controller.reports.SearchNoticeController.java

private ZipOutputStream addFilesToZip(final InputStream inputStream, final String noticeNo,
        final ZipOutputStream out) {
    final byte[] buffer = new byte[1024];
    try {// ww  w  . j  a  v  a 2s  .co m
        out.setLevel(Deflater.DEFAULT_COMPRESSION);
        out.putNextEntry(new ZipEntry(noticeNo.replaceAll("/", "_")));
        int len;
        while ((len = inputStream.read(buffer)) > 0)
            out.write(buffer, 0, len);
        inputStream.close();

    } catch (final IllegalArgumentException iae) {
        LOGGER.error(EXCEPTION_IN_ADDFILESTOZIP, iae);
    } catch (final FileNotFoundException fnfe) {
        LOGGER.error(EXCEPTION_IN_ADDFILESTOZIP, fnfe);
    } catch (final IOException ioe) {
        LOGGER.error(EXCEPTION_IN_ADDFILESTOZIP, ioe);
    }
    return out;
}

From source file:fr.simon.marquis.secretcodes.util.ExportContentProvider.java

private void saveZipFile() {
    File[] files = getContext().getFilesDir().listFiles();
    String zipPath = getContext().getFilesDir().getAbsolutePath() + "/" + ZIP_FILE_NAME;
    try {/* w w  w  .  j a  v  a2s.c  o  m*/
        BufferedInputStream origin = null;
        FileOutputStream zipFile = new FileOutputStream(zipPath);

        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(zipFile));

        byte data[] = new byte[BUFFER];
        for (int i = 0; i < files.length; i++) {
            FileInputStream fi = new FileInputStream(files[i]);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(
                    files[i].getAbsolutePath().substring(files[i].getAbsolutePath().lastIndexOf("/") + 1));
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }

        out.close();
        Log.d(this.getClass().getSimpleName(),
                "zipFile created at " + zipPath + " with " + files.length + " files");
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(this.getClass().getSimpleName(),
                "error while zipping at " + zipPath + " with " + files.length + " files", e);
    }

}

From source file:com.centurylink.mdw.common.service.JsonExport.java

/**
 * Default behavior adds zip entries for each property on the first (non-mdw) top-level object.
 *//*from  w w w.  j a v a2 s  .c o m*/
public String exportZipBase64() throws JSONException, IOException {
    Map<String, JSONObject> objectMap = JsonUtil.getJsonObjects(jsonable.getJson());
    JSONObject mdw = null;
    JSONObject contents = null;
    for (String name : objectMap.keySet()) {
        if ("mdw".equals(name))
            mdw = objectMap.get(name);
        else if (contents == null)
            contents = objectMap.get(name);
    }
    if (contents == null)
        throw new IOException("Cannot find expected contents property");
    else
        objectMap = JsonUtil.getJsonObjects(contents);
    if (mdw != null)
        objectMap.put(".mdw", mdw);

    byte[] buffer = new byte[ZIP_BUFFER_KB * 1024];
    ZipOutputStream zos = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        zos = new ZipOutputStream(outputStream);
        for (String name : objectMap.keySet()) {
            JSONObject json = objectMap.get(name);
            ZipEntry ze = new ZipEntry(name);
            zos.putNextEntry(ze);
            InputStream inputStream = new ByteArrayInputStream(json.toString(2).getBytes());
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
        }
    } finally {
        if (zos != null) {
            zos.closeEntry();
            zos.close();
        }
    }
    byte[] bytes = outputStream.toByteArray();
    return new String(Base64.encodeBase64(bytes));
}

From source file:com.aurel.track.admin.customize.category.report.ReportBL.java

/**
 * Zips a directory content into a zip stream
 * @param dirZip//from   www.ja va2s . c o  m
 * @param zipOut
 * @param rootPath
 */
public static void zipFiles(File dirZip, ZipOutputStream zipOut, String rootPath) {
    try {
        // get a listing of the directory content
        File[] dirList = dirZip.listFiles();
        byte[] readBuffer = new byte[2156];
        int bytesIn;
        // loop through dirList, and zip the files
        for (int i = 0; i < dirList.length; i++) {
            File f = dirList[i];
            if (f.isDirectory()) {
                // if the File object is a directory, call this
                // function again to add its content recursively
                String filePath = f.getAbsolutePath();
                zipFiles(new File(filePath), zipOut, rootPath);
                // loop again
                continue;
            }
            // if we reached here, the File object f was not a directory
            // create a FileInputStream on top of f
            FileInputStream fis = new FileInputStream(f);
            // create a new zip entry
            ZipEntry anEntry = new ZipEntry(
                    f.getAbsolutePath().substring(rootPath.length() + 1, f.getAbsolutePath().length()));
            // place the zip entry in the ZipOutputStream object
            zipOut.putNextEntry(anEntry);
            // now write the content of the file to the ZipOutputStream
            while ((bytesIn = fis.read(readBuffer)) != -1) {
                zipOut.write(readBuffer, 0, bytesIn);
            }
            // close the Stream
            fis.close();
        }

    } catch (Exception e) {
        LOGGER.error("Zip the " + dirZip.getName() + " failed with " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:org.alfresco.repo.web.scripts.custommodel.CustomModelImportTest.java

private File createZip(ZipEntryContext... zipEntryContexts) {
    File zipFile = TempFileProvider.createTempFile(getClass().getSimpleName(), ".zip");
    tempFiles.add(zipFile);//from w ww  .  j a  v a 2  s  .  co m

    byte[] buffer = new byte[BUFFER_SIZE];
    try {
        OutputStream out = new BufferedOutputStream(new FileOutputStream(zipFile), BUFFER_SIZE);
        ZipOutputStream zos = new ZipOutputStream(out);

        for (ZipEntryContext context : zipEntryContexts) {
            ZipEntry zipEntry = new ZipEntry(context.getZipEntryName());
            zos.putNextEntry(zipEntry);

            InputStream input = context.getEntryContent();
            int len;
            while ((len = input.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            input.close();
        }
        zos.closeEntry();
        zos.close();
    } catch (IOException ex) {
        fail("couldn't create zip file.");
    }

    return zipFile;
}

From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java

private void addToZipOutputStream(String filePath, ZipOutputStream zip) throws IOException {
    byte[] buf = new byte[1024];
    int len;//from   ww w.  ja  v a 2 s.c  o  m
    File input = new File(filePath);
    try (FileInputStream in = new FileInputStream(input)) {
        zip.putNextEntry(new ZipEntry(input.getName()));
        while ((len = in.read(buf)) > 0) {
            zip.write(buf, 0, len);
        }
        zip.flush();
    }
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private String firmarImagen(int fileName) throws IOException {

    String result = "";
    try {/* w ww. j a v a2  s . c om*/
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();
        String theFolder = s + "/" + "archivos";

        FileOutputStream fos = new FileOutputStream(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);

        String file1Name = theFolder + "/" + Integer.toString(fileName) + ".jpg";
        File image = new File(file1Name);

        ZipEntry zipEntry = new ZipEntry(image.getName());
        zos.putNextEntry(zipEntry);
        FileInputStream fileInputStream = new FileInputStream(image);

        byte[] buf = new byte[2048];
        int bytesRead;

        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            zos.write(buf, 0, bytesRead);
        }
        zos.closeEntry();
        zos.close();
        fos.close();

        Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
        byte[] data = Files.readAllBytes(path);
        byte[] byteArray = Base64.encodeBase64(data);
        String b64 = new String(byteArray);

        result = firma(b64, Integer.toString(fileName), "pruebita");
        System.out.println("User : " + idSimulatedUser + " ENVIADO");
        nFilesSend++;

    } catch (FileNotFoundException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (WriterException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "http://" + result;
}

From source file:org.akvo.flow.service.DataSyncService.java

/**
 * writes the contents of text to a zip entry within the Zip file behind zos
 * named fileName/*from   ww  w. ja va  2 s. co  m*/
 *
 * @param zos
 * @param text
 * @param fileName
 * @throws java.io.IOException
 */
private void writeTextToZip(ZipOutputStream zos, String text, String fileName) throws IOException {
    Log.i(TAG, "Writing zip entry");
    zos.putNextEntry(new ZipEntry(fileName));
    byte[] allBytes = text.getBytes("UTF-8");
    zos.write(allBytes, 0, allBytes.length);
    zos.closeEntry();
    Log.i(TAG, "Entry Complete");
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private void consultarFirma(int fileNameId) {
    try {/*  w  ww. ja  v  a2 s  .c om*/
        FileOutputStream fos = new FileOutputStream(
                userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.zip");
        ZipOutputStream zos = new ZipOutputStream(fos);

        String file1Name = userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.png";
        File image = new File(file1Name);

        ZipEntry zipEntry = new ZipEntry(image.getName());
        zos.putNextEntry(zipEntry);
        FileInputStream fileInputStream = new FileInputStream(image);

        byte[] buf = new byte[2048];
        int bytesRead;

        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            zos.write(buf, 0, bytesRead);
        }
        zos.closeEntry();
        zos.close();
        fos.close();

        Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileNameId) + "Firmada.zip");

        byte[] data = Files.readAllBytes(path);
        byte[] byteArray = Base64.encodeBase64(data);
        String b64 = new String(byteArray);

        System.out.println(consultaFirma(b64, Integer.toString(fileNameId) + "Firmada"));

        nFilesVerified++;
        System.out.println("User : " + idSimulatedUser + " FIRMA VERIFICADA");
    } catch (IOException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        nNotFileFound++;
    } catch (IOException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        nVerifyErrors++;
    }
}