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.kuali.coeus.s2sgen.impl.print.FormPrintServiceImpl.java

protected void addFileToZip(String path, String sourceFile, ZipOutputStream zipOutputStream) throws Exception {
    File attachmentFile = new File(sourceFile);
    if (attachmentFile.isDirectory()) {
        addFolderToZip(path, sourceFile, zipOutputStream);
    } else {//from w  w  w.  j a v a 2 s. co  m
        byte[] buffer = new byte[1024];
        int length;
        try (FileInputStream fileInputStream = new FileInputStream(attachmentFile)) {
            zipOutputStream.putNextEntry(new ZipEntry(path + "/" + attachmentFile.getName()));
            while ((length = fileInputStream.read(buffer)) > 0) {
                zipOutputStream.write(buffer, 0, length);
            }
        }
    }
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

private void addFileToZip(final String basePath, final File file, final ZipOutputStream zipout)
        throws IOException {
    if (file == null || !file.exists()) {
        return;//  ww  w .jav a  2  s .  c om
    }

    final String filePath = file.getPath();
    if (file.isDirectory()) {
        if (!isExcluded(filePath, true, basePath)) {
            final File[] files = file.listFiles();
            for (final File f : files) {
                addFileToZip(basePath, f, zipout);
            }
        }
    } else {
        if (!isExcluded(filePath, false, basePath)) {
            final byte[] buf = new byte[65536];
            int len;
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                zipout.putNextEntry(new ZipEntry(filePath.substring(basePath.length() + 1)));
                while ((len = in.read(buf)) > 0) {
                    zipout.write(buf, 0, len);
                }
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        }
    }
}

From source file:org.brandroid.openmanager.util.FileManager.java

private void zipIt(OpenPath file, ZipOutputStream zout, int totalSize, String relativePath) throws IOException {
    byte[] data = new byte[BUFFER];
    int read;/*from   w  ww .  j  ava 2 s.co  m*/

    if (file.isFile()) {
        String name = file.getPath();
        if (relativePath != null && name.startsWith(relativePath))
            name = name.substring(relativePath.length());
        ZipEntry entry = new ZipEntry(name);
        zout.putNextEntry(entry);
        BufferedInputStream instream = new BufferedInputStream(file.getInputStream());
        //Logger.LogVerbose("zip_folder file name = " + entry.getName());
        int size = (int) file.length();
        int pos = 0;
        while ((read = instream.read(data, 0, BUFFER)) != -1) {
            pos += read;
            zout.write(data, 0, read);
            updateProgress(pos, size, totalSize);
        }

        zout.closeEntry();
        instream.close();

    } else if (file.isDirectory()) {
        //Logger.LogDebug("zip_folder dir name = " + file.getPath());
        for (OpenPath kid : file.list())
            totalSize += kid.length();
        for (OpenPath kid : file.list())
            zipIt(kid, zout, totalSize, relativePath);
    }
}

From source file:it.eng.spagobi.tools.downloadFiles.service.DownloadZipAction.java

public void createZipFromFiles(Vector<File> files, String outputFileName, String folderName)
        throws IOException {
    logger.debug("IN");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
    // Compress the files 
    for (Iterator iterator = files.iterator(); iterator.hasNext();) {
        File file = (File) iterator.next();

        FileInputStream in = new FileInputStream(file);

        String fileName = file.getName();
        // The name to Inssert: remove the parameter folder
        //         int lastIndex=folderName.length();
        //         String fileToInsert=fileName.substring(lastIndex+1);

        logger.debug("Adding to zip entry " + fileName);
        ZipEntry zipEntry = new ZipEntry(fileName);

        // Add ZIP entry to output stream. 
        out.putNextEntry(zipEntry);//from   ww w .  j a  v a2 s .c  om

        // Transfer bytes from the file to the ZIP file 
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry 
        out.closeEntry();
        in.close();
    }
    // Complete the ZIP file 
    out.close();
    logger.debug("OUT");
}

From source file:cdr.forms.SwordDepositHandler.java

private File makeZipFile(gov.loc.mets.DocumentRoot metsDocumentRoot,
        IdentityHashMap<DepositFile, String> filenames) {

    // Get the METS XML

    String metsXml = serializeMets(metsDocumentRoot);

    // Create the zip file

    File zipFile;// w w w.j  a v  a 2  s  . c om

    try {
        zipFile = File.createTempFile("tmp", ".zip");
    } catch (IOException e) {
        throw new Error(e);
    }

    FileOutputStream fileOutput;

    try {
        fileOutput = new FileOutputStream(zipFile);
    } catch (FileNotFoundException e) {
        throw new Error(e);
    }

    ZipOutputStream zipOutput = new ZipOutputStream(fileOutput);

    try {

        ZipEntry entry;

        // Write the METS

        entry = new ZipEntry("mets.xml");
        zipOutput.putNextEntry(entry);

        PrintStream xmlPrintStream = new PrintStream(zipOutput);
        xmlPrintStream.print(metsXml);

        // Write files

        for (DepositFile file : filenames.keySet()) {

            if (!file.isExternal()) {

                entry = new ZipEntry(filenames.get(file));
                zipOutput.putNextEntry(entry);

                FileInputStream fileInput = new FileInputStream(file.getFile());

                byte[] buffer = new byte[1024];
                int length;

                while ((length = fileInput.read(buffer)) != -1)
                    zipOutput.write(buffer, 0, length);

                fileInput.close();

            }

        }

        zipOutput.finish();
        zipOutput.close();

        fileOutput.close();

    } catch (IOException e) {

        throw new Error(e);

    }

    return zipFile;

}

From source file:com.castlemock.web.basis.web.mvc.controller.project.ProjectsOverviewController.java

/**
 * The method provides the functionality to update, delete and export projects. It bases the requested functionality based
 * on the provided action.//from ww  w .  ja  v a2  s  .com
 * @param action The action is used to determined which action/functionality the perform.
 * @param projectModifierCommand The project overview command contains which ids going to be updated, deleted or exported.
 * @param response The HTTP servlet response
 * @return The model depending in which action was requested.
 */
@PreAuthorize("hasAuthority('READER') or hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView projectFunctionality(@RequestParam String action,
        @ModelAttribute ProjectModifierCommand projectModifierCommand, HttpServletResponse response) {
    LOGGER.debug("Project action requested: " + action);
    if (EXPORT_PROJECTS.equalsIgnoreCase(action)) {
        if (projectModifierCommand.getProjects().length == 0) {
            return redirect();
        }

        ZipOutputStream zipOutputStream = null;
        InputStream inputStream = null;
        final String outputFilename = tempFilesFolder + SLASH + "exported-projects-" + new Date().getTime()
                + ".zip";
        try {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(outputFilename));
            for (String project : projectModifierCommand.getProjects()) {
                final String[] projectData = project.split(SLASH);
                if (projectData.length != 2) {
                    continue;
                }

                final String projectTypeUrl = projectData[0];
                final String projectId = projectData[1];
                final String exportedProject = projectServiceFacade.exportProject(projectTypeUrl, projectId);
                final byte[] data = exportedProject.getBytes();
                final String filename = "exported-project-" + projectTypeUrl + "-" + projectId + ".xml";
                zipOutputStream.putNextEntry(new ZipEntry(filename));
                zipOutputStream.write(data, 0, data.length);
                zipOutputStream.closeEntry();
            }
            zipOutputStream.close();

            inputStream = new FileInputStream(outputFilename);
            IOUtils.copy(inputStream, response.getOutputStream());

            response.setContentType("application/zip");
            response.flushBuffer();
            return null;
        } catch (IOException exception) {
            LOGGER.error("Unable to export multiple projects and zip them", exception);
        } finally {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the zip output stream", exception);
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the input stream", exception);
                }
            }
            fileManager.deleteUploadedFile(outputFilename);
        }
    } else if (DELETE_PROJECTS.equalsIgnoreCase(action)) {
        List<ProjectDto> projects = new LinkedList<ProjectDto>();
        for (String project : projectModifierCommand.getProjects()) {
            final String[] projectData = project.split(SLASH);

            if (projectData.length != 2) {
                continue;
            }

            final String projectTypeUrl = projectData[0];
            final String projectId = projectData[1];
            final ProjectDto projectDto = projectServiceFacade.findOne(projectTypeUrl, projectId);
            projects.add(projectDto);
        }
        ModelAndView model = createPartialModelAndView(DELETE_PROJECTS_PAGE);
        model.addObject(PROJECTS, projects);
        model.addObject(DELETE_PROJECTS_COMMAND, new DeleteProjectsCommand());
        return model;
    }

    return redirect();
}

From source file:org.dspace.app.itemexport.ItemExport.java

private static void zipFiles(File cpFile, String strSource, String strTarget, ZipOutputStream cpZipOutputStream)
        throws Exception {
    int byteCount;
    final int DATA_BLOCK_SIZE = 2048;
    FileInputStream cpFileInputStream = null;
    if (cpFile.isDirectory()) {
        File[] fList = cpFile.listFiles();
        for (int i = 0; i < fList.length; i++) {
            zipFiles(fList[i], strSource, strTarget, cpZipOutputStream);
        }//from   w  w  w  . j av a2s. c om
    } else {
        try {
            if (cpFile.getAbsolutePath().equalsIgnoreCase(strTarget)) {
                return;
            }
            String strAbsPath = cpFile.getPath();
            String strZipEntryName = strAbsPath.substring(strSource.length() + 1, strAbsPath.length());

            // byte[] b = new byte[ (int)(cpFile.length()) ];

            cpFileInputStream = new FileInputStream(cpFile);

            ZipEntry cpZipEntry = new ZipEntry(strZipEntryName);
            cpZipOutputStream.putNextEntry(cpZipEntry);

            byte[] b = new byte[DATA_BLOCK_SIZE];
            while ((byteCount = cpFileInputStream.read(b, 0, DATA_BLOCK_SIZE)) != -1) {
                cpZipOutputStream.write(b, 0, byteCount);
            }

            // cpZipOutputStream.write(b, 0, (int)cpFile.length());
        } finally {
            if (cpFileInputStream != null) {
                cpFileInputStream.close();
            }
            cpZipOutputStream.closeEntry();
        }
    }
}

From source file:fr.univrouen.poste.services.ZipService.java

public void writeZip(List<PosteCandidature> posteCandidatures, OutputStream destStream)
        throws IOException, SQLException {

    ZipOutputStream out = new ZipOutputStream(destStream);

    for (PosteCandidature posteCandidature : posteCandidatures) {
        String folderName = posteCandidature.getPoste().getNumEmploi().concat("/");
        folderName = folderName.concat(posteCandidature.getCandidat().getNom().concat("-"));
        folderName = folderName.concat(posteCandidature.getCandidat().getPrenom().concat("-"));
        folderName = folderName.concat(posteCandidature.getCandidat().getNumCandidat().concat("/"));
        for (PosteCandidatureFile posteCandidatureFile : posteCandidature.getCandidatureFiles()) {
            String fileName = posteCandidatureFile.getId().toString().concat("-")
                    .concat(posteCandidatureFile.getFilename());
            String folderFileName = folderName.concat(fileName);
            out.putNextEntry(new ZipEntry(folderFileName));
            InputStream inputStream = posteCandidatureFile.getBigFile().getBinaryFile().getBinaryStream();
            BufferedInputStream bufInputStream = new BufferedInputStream(inputStream, BUFFER);
            byte[] bytes = new byte[BUFFER];
            int length;
            while ((length = bufInputStream.read(bytes)) >= 0) {
                out.write(bytes, 0, length);
            }/*from w ww  .  ja  v a  2  s.co  m*/
            out.closeEntry();
        }
    }
    out.close();
}

From source file:com.wegas.core.jcr.content.ContentConnector.java

/**
 * Compress directory and children to ZipOutputStream. Warning: metadatas
 * are not included due to zip limitation
 *
 * @param out  a ZipOutputStream to write files to
 * @param path root path to compress//from   w  ww  . ja  v  a2  s.  c om
 * @throws RepositoryException
 * @throws IOException
 */
public void zipDirectory(ZipOutputStream out, String path) throws RepositoryException, IOException {
    AbstractContentDescriptor node = DescriptorFactory.getDescriptor(path, this);
    DirectoryDescriptor root;
    if (node.isDirectory()) {
        root = (DirectoryDescriptor) node;
    } else {
        return;
    }
    List<AbstractContentDescriptor> list = root.list();

    ZipEntry entry;
    for (AbstractContentDescriptor item : list) {
        entry = item.getZipEntry();
        try {
            out.putNextEntry(entry);
        } catch (ZipException ex) {
            logger.warn("error");
        }
        if (item.isDirectory()) {
            zipDirectory(out, item.getFullPath());
        } else {
            byte[] write = ((FileDescriptor) item).getBytesData();
            out.write(write, 0, write.length);
        }
    }
    out.closeEntry();
}