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:com.ephesoft.dcma.util.FileUtils.java

/**
 * To get output Stream from Zip./*from ww w .j  a v  a2  s.  c  o m*/
 * 
 * @param zipName {@link String}
 * @param fileName {@link String}
 * @return {@link InputStream}
 * @throws FileNotFoundException in case of error
 * @throws IOException in case of error
 */
public static OutputStream getOutputStreamFromZip(final String zipName, final String fileName)
        throws FileNotFoundException, IOException {
    ZipOutputStream stream = null;
    stream = new ZipOutputStream(new FileOutputStream(new File(zipName + ZIP_FILE_EXT)));
    ZipEntry zipEntry = new ZipEntry(fileName);
    stream.putNextEntry(zipEntry);

    return stream;
}

From source file:com.joliciel.jochre.lexicon.TextFileLexicon.java

public void serialize(File memoryBaseFile) {
    LOG.debug("serialize");
    boolean isZip = false;
    if (memoryBaseFile.getName().endsWith(".zip"))
        isZip = true;/* www.j  a  va 2s .com*/

    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    ZipOutputStream zos = null;
    try {
        fos = new FileOutputStream(memoryBaseFile);
        if (isZip) {
            zos = new ZipOutputStream(fos);
            zos.putNextEntry(new ZipEntry("lexicon.obj"));
            out = new ObjectOutputStream(zos);
        } else {
            out = new ObjectOutputStream(fos);
        }

        try {
            out.writeObject(this);
        } finally {
            out.flush();
            out.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.android.tradefed.util.FileUtil.java

/**
 * Recursively adds given file and its contents to ZipOutputStream
 *
 * @param out/* ww  w . j a v a2 s . c om*/
 *            the {@link ZipOutputStream}
 * @param file
 *            the {@link File} to add to the stream
 * @param relativePathSegs
 *            the relative path of file, including separators
 * @throws IOException
 *             if failed to add file to zip
 */
private static void addToZip(ZipOutputStream out, File file, List<String> relativePathSegs) throws IOException {
    relativePathSegs.add(file.getName());
    if (file.isDirectory()) {
        // note: it appears even on windows, ZipEntry expects '/' as a path
        // separator
        relativePathSegs.add("/");
    }
    ZipEntry zipEntry = new ZipEntry(buildPath(relativePathSegs));
    out.putNextEntry(zipEntry);
    if (file.isFile()) {
        writeToStream(file, out);
    }
    out.closeEntry();
    if (file.isDirectory()) {
        // recursively add contents
        File[] subFiles = file.listFiles();
        if (subFiles == null) {
            throw new IOException(String.format("Could not read directory %s", file.getAbsolutePath()));
        }
        for (File subFile : subFiles) {
            addToZip(out, subFile, relativePathSegs);
        }
        // remove the path separator
        relativePathSegs.remove(relativePathSegs.size() - 1);
    }
    // remove the last segment, added at beginning of method
    relativePathSegs.remove(relativePathSegs.size() - 1);
}

From source file:gdt.data.entity.ArchiveHandler.java

private static void appendToZip(String directoryToZip$, File file, ZipOutputStream zos) {
    try {//from  w ww  . ja va  2 s .c om
        FileInputStream fis = new FileInputStream(file);
        String zipFile$ = file.getPath().substring(directoryToZip$.length() + 1, file.getPath().length());
        //System.out.println("Writing '" + zipFile$ + "' to zip file");
        ZipEntry zipEntry = new ZipEntry(zipFile$);
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }
        zos.closeEntry();
        fis.close();
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }
}

From source file:com.thoughtworks.go.util.ZipUtil.java

private void addDirectory(ZipPath path, File source, ZipOutputStream zip, boolean excludeRootDir)
        throws IOException {
    if (excludeRootDir) {
        addDirContents(path, source, zip);
        return;/*from   w ww . j a v a  2  s  .  c  o  m*/
    }
    ZipPath newPath = path.with(source);
    zip.putNextEntry(newPath.asZipEntryDirectory());
    addDirContents(newPath, source, zip);
}

From source file:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java

private InputStream createSampleZip() throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    zipOutputStream.putNextEntry(new ZipEntry("a/"));
    zipOutputStream.closeEntry();//w ww  .ja  va 2  s  .  c  o m
    zipOutputStream.putNextEntry(new ZipEntry("a/b.txt"));
    IOUtils.write("ab", zipOutputStream);
    zipOutputStream.closeEntry();
    zipOutputStream.putNextEntry(new ZipEntry("c/"));
    zipOutputStream.closeEntry();
    zipOutputStream.putNextEntry(new ZipEntry("c/d.txt"));
    IOUtils.write("cd", zipOutputStream);
    zipOutputStream.closeEntry();
    zipOutputStream.close();
    return new ByteArrayInputStream(outputStream.toByteArray());
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

/** Obtiene el fichero OOXMLK firmado.
 * @param signatureData/*from  ww  w . j av  a 2s  .co  m*/
 * @return Fichero OOXML firmado
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
public final byte[] outputSignedOfficeOpenXMLDocument(final byte[] signatureData)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {

    final ByteArrayOutputStream signedOOXMLOutputStream = new ByteArrayOutputStream();

    final String signatureZipEntryName = "_xmlsignatures/sig-" + UUID.randomUUID().toString() + ".xml"; //$NON-NLS-1$ //$NON-NLS-2$

    /*
     * Copy the original OOXML content to the signed OOXML package. During
     * copying some files need to changed.
     */
    final ZipOutputStream zipOutputStream = copyOOXMLContent(signatureZipEntryName, signedOOXMLOutputStream);

    // Add the OOXML XML signature file to the OOXML package.
    zipOutputStream.putNextEntry(new ZipEntry(signatureZipEntryName));
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();

    return signedOOXMLOutputStream.toByteArray();
}

From source file:de.hybris.platform.impex.jalo.ImpExMediasImportTest.java

/**
 * Calls the <code>importData</code> method of given handler with an zip-file path in different formats.
 * /*from w ww .j  a v  a  2 s.  co m*/
 * @param handler
 *           handler which will be used for test
 * @param media
 *           media where the data will be imported to
 */
private void mediaImportFromZip(final MediaDataHandler handler, final Media media) {
    File testFile = null;
    try {
        testFile = File.createTempFile("mediaImportTest", ".zip");
        final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testFile));
        zos.putNextEntry(new ZipEntry(new File("files", "dummy.txt").getPath()));
        zos.putNextEntry(new ZipEntry(new File("files", "test.txt").getPath()));
        final PrintWriter printer = new PrintWriter(zos);
        printer.print("testest");
        printer.flush();
        zos.flush();
        printer.close();
        zos.close();
    } catch (final IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    final String unixPathRel = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToUnix(testFile.getPath()) + "&files/test.txt";
    final String unixPathAbs = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToUnix(testFile.getAbsolutePath()) + "&files/test.txt";
    final String winPathRel = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToWindows(testFile.getPath()) + "&files\\test.txt";
    final String winPathAbs = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToWindows(testFile.getAbsolutePath()) + "&files\\test.txt";
    try {
        mediaImport(handler, media, unixPathRel, "testest");
        mediaImport(handler, media, unixPathAbs, "testest");
        mediaImport(handler, media, winPathRel, "testest");
        mediaImport(handler, media, winPathAbs, "testest");
    } catch (final Exception e) {
        fail(e.getMessage());
    }
    if (!testFile.delete()) {
        fail("Can not delete temp file: " + testFile.getPath());
    }
}

From source file:com.jd.survey.web.reports.ReportController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "spss", produces = "text/html")
public void surveySPSSExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {//from   w ww . j  a va  2s  .c  om
        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../accessDenied");
            //throw new AccessDeniedException("Unauthorized access attempt");
        }

        String metadataFileName = "survey" + surveyDefinitionId + ".sps";
        String dataFileName = "survey" + surveyDefinitionId + ".dat";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipfile = new ZipOutputStream(baos);

        //metadata    
        zipfile.putNextEntry(new ZipEntry(metadataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSMetadata(surveyDefinitionId, dataFileName));
        //data
        zipfile.putNextEntry(new ZipEntry(dataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSData(surveyDefinitionId));
        zipfile.close();

        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinitionId + "_spss.zip");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.write(baos.toByteArray());
        servletOutputStream.flush();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:de.hybris.platform.impex.jalo.ImpExMediasImportTest.java

/**
 * Calls the <code>importData</code> method of given handler with an zip-file path in different formats.
 * //from w  ww  .ja v  a2 s  .  c o m
 * @param handler
 *           handler which will be used for test
 * @param media
 *           media where the data will be imported to
 */
private void mediaImportFromMediasMedia(final MediaDataHandler handler, final Media media,
        final ImpExImportCronJob cronJob) {
    MediaDataHandler myHandler = handler;
    File testFile = null;
    try {
        testFile = File.createTempFile("mediaImportTest", ".zip");
        final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testFile));
        zos.putNextEntry(new ZipEntry(new File("notunzip\\notexist.txt").getPath()));
        zos.putNextEntry(new ZipEntry(new File("files\\dummy.txt").getPath()));
        zos.putNextEntry(new ZipEntry(new File("files\\test.txt").getPath()));
        final PrintWriter printer = new PrintWriter(zos);
        printer.print("testest");
        printer.flush();
        zos.flush();
        printer.close();
        zos.close();
    } catch (final IOException e) {
        fail(e.getMessage());
    }
    try {
        final Media mediasMedia = ImpExManager.getInstance().createImpExMedia("mediasMedia", "UTF-8",
                new FileInputStream(testFile));
        cronJob.setMediasMedia(mediasMedia);

        mediaImport(myHandler, media, "files/test.txt", "testest");
        myHandler.cleanUp();
        myHandler = new DefaultCronJobMediaDataHandler(cronJob);
        mediaImport(myHandler, media, "files\\test.txt", "testest");
        myHandler.cleanUp();
        cronJob.setMediasTarget("files");
        myHandler = new DefaultCronJobMediaDataHandler(cronJob);
        mediaImport(myHandler, media, "test.txt", "testest");
        myHandler.cleanUp();
        cronJob.setMediasTarget(null);
    } catch (final Exception e) {
        fail(e.getMessage());
    }
    if (!testFile.delete()) {
        fail("Can not delete temp file: " + testFile.getPath());
    }
}