Example usage for java.util.zip ZipOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

From source file:br.univali.celine.lms.utils.zip.Zip.java

private void addDir(File dirObj, ZipOutputStream out, int rootLen) throws IOException {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            addDir(files[i], out, rootLen);
            continue;
        }/*from w  ww. j  ava 2s  . c  o  m*/

        FileInputStream in = new FileInputStream(files[i].getAbsolutePath());

        out.putNextEntry(new ZipEntry(files[i].getAbsolutePath().substring(rootLen)));

        int len;
        while ((len = in.read(tmpBuf)) > 0) {
            out.write(tmpBuf, 0, len);
        }

        out.closeEntry();
        in.close();
    }
}

From source file:com.sangupta.jerry.util.ZipUtils.java

/**
 * Compresses the provided file into ZIP format adding a '.ZIP' at the end
 * of the filename.//from  w  w w . j  ava2 s  . c o  m
 * 
 * @param filePath
 *            the file path that needs to be compressed
 * 
 * @return returns the absolute path of the ZIP file.
 */
public String createZipFile(String filePath) {
    LOGGER.debug("Starting compression of " + filePath);

    String zipFilename = filePath + ".zip";
    LOGGER.debug("Creating zip file at " + zipFilename);

    byte[] buf = new byte[1024];

    ZipOutputStream stream = null;
    FileInputStream input = null;
    try {
        // Create the ZIP file
        stream = new ZipOutputStream(new FileOutputStream(zipFilename));

        // Compress the file
        File file = new File(filePath);
        input = new FileInputStream(file);

        // Add ZIP entry to output stream.
        stream.putNextEntry(new ZipEntry(file.getName()));

        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = input.read(buf)) > 0) {
            stream.write(buf, 0, len);
        }

        // Complete the entry
        stream.closeEntry();
    } catch (IOException e) {
        LOGGER.error("Unable to compress file " + filePath, e);
    } finally {
        IOUtils.closeQuietly(input);

        // Complete the ZIP file
        IOUtils.closeQuietly(stream);
    }

    return zipFilename;
}

From source file:com.funambol.framework.tools.FileArchiver.java

private void createEntry(ZipOutputStream zipOutputStream, String entryName) throws FileArchiverException {
    ZipEntry entry = new ZipEntry(entryName);
    try {// w w  w . j  a v  a  2s  . co  m
        zipOutputStream.putNextEntry(entry);
    } catch (IOException e) {
        throw new FileArchiverException("An error occurred adding entry '" + entryName + "' to the zip file.",
                e);
    }
}

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

private String firmarImagen(int fileName) throws IOException {

    String result = "";
    try {/*from ww w .  j  a va2s .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:com.juancarlosroot.threads.SimulatedUser.java

private void consultarFirma(int fileNameId) {
    try {/*from  www. ja  v a 2  s . c  o m*/
        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++;
    }
}

From source file:pl.betoncraft.betonquest.editor.model.PackageSet.java

/**
 * Saves the package to a .zip file.//from w w w  .  java  2  s.  c  o m
 * 
 * @param zipFile
 */
public void saveToZip(File zip) {
    try {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zip));
        for (QuestPackage pack : packages) {
            String prefix = pack.getName().get().replace("-", File.separator) + File.separator;
            // save main.yml file
            ZipEntry main = new ZipEntry(prefix + "main.yml");
            out.putNextEntry(main);
            pack.printMainYAML(out);
            out.closeEntry();
            // save conversation files
            for (Conversation conv : pack.getConversations()) {
                ZipEntry conversation = new ZipEntry(
                        prefix + "conversations" + File.separator + conv.getId().get() + ".yml");
                out.putNextEntry(conversation);
                pack.printConversationYaml(out, conv);
                out.closeEntry();
            }
            // save events.yml file
            ZipEntry events = new ZipEntry(prefix + "events.yml");
            out.putNextEntry(events);
            pack.printEventsYaml(out);
            out.closeEntry();
            // save conditions.yml file
            ZipEntry conditions = new ZipEntry(prefix + "conditions.yml");
            out.putNextEntry(conditions);
            pack.printConditionsYaml(out);
            out.closeEntry();
            // save objectives.yml file
            ZipEntry objectives = new ZipEntry(prefix + "objectives.yml");
            out.putNextEntry(objectives);
            pack.printObjectivesYaml(out);
            out.closeEntry();
            // save items.yml file
            ZipEntry items = new ZipEntry(prefix + "items.yml");
            out.putNextEntry(items);
            pack.printItemsYaml(out);
            out.closeEntry();
            // save journal.yml file
            ZipEntry journal = new ZipEntry(prefix + "journal.yml");
            out.putNextEntry(journal);
            pack.printJournalYaml(out);
            out.closeEntry();
        }
        // done
        out.close();
    } catch (Exception e) {
        ExceptionController.display(e);
    }
}

From source file:net.solarnetwork.node.backup.DefaultBackupManager.java

@Override
public void exportBackupArchive(String backupKey, OutputStream out) throws IOException {
    final BackupService service = activeBackupService();
    if (service == null) {
        return;/*from  ww w .  j  a  v a 2 s.  com*/
    }

    final Backup backup = service.backupForKey(backupKey);
    if (backup == null) {
        return;
    }

    // create the zip archive for the backup files
    ZipOutputStream zos = new ZipOutputStream(out);
    try {
        BackupResourceIterable resources = service.getBackupResources(backup);
        for (BackupResource r : resources) {
            zos.putNextEntry(new ZipEntry(r.getBackupPath()));
            FileCopyUtils.copy(r.getInputStream(), new FilterOutputStream(zos) {

                @Override
                public void close() throws IOException {
                    // FileCopyUtils closed the stream, which we don't want here
                }

            });
        }
        resources.close();
    } finally {
        zos.flush();
        zos.finish();
        zos.close();
    }
}

From source file:es.urjc.mctwp.bbeans.research.image.DownloadBean.java

private void addFileToZos(ZipOutputStream zos, File file, String path) throws IOException {

    //Prepare entry path
    String entry = null;// w  w  w  .ja v a2  s . c o  m
    if (path != null && !path.isEmpty())
        entry = path + "/" + file.getName();
    else
        entry = file.getName();

    //Create zip entry
    ZipEntry ze = new ZipEntry(entry);
    zos.putNextEntry(ze);

    //Write zip entry
    FileInputStream fileIS = new FileInputStream(file);
    while (fileIS.available() > 0) {
        byte bytes[] = new byte[fileIS.available()];
        fileIS.read(bytes);
        zos.write(bytes);
    }

    zos.flush();
    fileIS.close();
}

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 ww w.j a v  a  2 s .co 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:edu.jhuapl.graphs.controller.GraphController.java

public static String zipGraphs(List<GraphObject> graphs, String tempDir, String userId) throws GraphException {
    if (graphs != null && graphs.size() > 0) {
        byte[] byteBuffer = new byte[1024];
        String zipFileName = getUniqueId(userId) + ".zip";

        try {/*from w w  w .j ava2s  .  c  o  m*/
            File zipFile = new File(tempDir, zipFileName);
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
            boolean hasGraphs = false;

            for (GraphObject graph : graphs) {
                if (graph != null) {
                    byte[] renderedGraph = graph.getRenderedGraph().getData();
                    ByteArrayInputStream in = new ByteArrayInputStream(renderedGraph);
                    int len;

                    zos.putNextEntry(new ZipEntry(graph.getImageFileName()));

                    while ((len = in.read(byteBuffer)) > 0) {
                        zos.write(byteBuffer, 0, len);
                    }

                    in.close();
                    zos.closeEntry();
                    hasGraphs = true;
                }
            }

            zos.close();

            if (hasGraphs) {
                return zipFileName;
            } else {
                return null;
            }
        } catch (IOException e) {
            throw new GraphException("Could not write zip", e);
        }
    }

    return null;
}