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:cross.io.misc.WorkflowZipper.java

private void addZipEntry(final int bufsize, final ZipOutputStream zos, final byte[] input_buffer,
        final File file, final HashSet<String> zipEntries) throws IOException {
    log.debug("Adding zip entry for file {}", file);
    if (file.exists() && file.isFile()) {
        // Use the file name for the ZipEntry name.
        final ZipEntry zip_entry = new ZipEntry(file.getName());
        if (zipEntries.contains(file.getName())) {
            log.info("Skipping duplicate zip entry {}", file.getName());
            return;
        } else {//w  w  w.j  av a 2  s.co m
            zipEntries.add(file.getName());
        }
        zos.putNextEntry(zip_entry);

        // Create a buffered input stream from the file stream.
        final FileInputStream in = new FileInputStream(file);
        // Read from source into buffer and write, thereby compressing
        // on the fly
        try (BufferedInputStream source = new BufferedInputStream(in, bufsize)) {
            // Read from source into buffer and write, thereby compressing
            // on the fly
            int len = 0;
            while ((len = source.read(input_buffer, 0, bufsize)) != -1) {
                zos.write(input_buffer, 0, len);
            }
            zos.flush();
        }
        zos.closeEntry();
    } else {
        log.warn("Skipping nonexistant file or directory {}", file);
    }
}

From source file:com.clustercontrol.collect.util.ZipCompresser.java

/**
 * ?????1????//from   w  w  w.jav a  2 s.co m
 * 
 * @param inputFileNameList ??
 * @param outputFileName ?
 * 
 * @return ???
 */
protected static synchronized void archive(ArrayList<String> inputFileNameList, String outputFileName)
        throws HinemosUnknown {
    m_log.debug("archive() output file = " + outputFileName);

    byte[] buf = new byte[128];
    BufferedInputStream in = null;
    ZipEntry entry = null;
    ZipOutputStream out = null;

    // ?
    if (outputFileName == null || "".equals(outputFileName)) {
        HinemosUnknown e = new HinemosUnknown("archive output fileName is null ");
        m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    }
    File zipFile = new File(outputFileName);
    if (zipFile.exists()) {
        if (zipFile.isFile() && zipFile.canWrite()) {
            m_log.debug("archive() output file = " + outputFileName
                    + " is exists & file & writable. initialize file(delete)");
            if (!zipFile.delete())
                m_log.debug("Fail to delete " + zipFile.getAbsolutePath());
        } else {
            HinemosUnknown e = new HinemosUnknown("archive output fileName is directory or not writable ");
            m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
            throw e;
        }
    }

    // ?
    try {
        // ????
        out = new ZipOutputStream(new FileOutputStream(outputFileName));

        for (String inputFileName : inputFileNameList) {
            m_log.debug("archive() input file name = " + inputFileName);

            // ????
            in = new BufferedInputStream(new FileInputStream(inputFileName));

            // ??
            String fileName = (new File(inputFileName)).getName();
            m_log.debug("archive() entry file name = " + fileName);
            entry = new ZipEntry(fileName);

            out.putNextEntry(entry);
            // ????
            int size;
            while ((size = in.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, size);
            }
            // ??
            out.closeEntry();
            in.close();
        }
        // ? out.flush();
        out.close();

    } catch (IOException e) {
        m_log.warn("archive() archive error : " + outputFileName + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        throw new HinemosUnknown("archive error " + outputFileName, e);

    } finally {

        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Save out to the same file that things were read in.
 * /*ww w . java2  s  .com*/
 * @throws IOException if an error occurs writing to the file
 */
public void save() throws IOException {
    if (validateData()) {

        final ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(_file));
        final Writer writer = new OutputStreamWriter(zipOut, Utilities.DEFAULT_CHARSET);

        zipOut.putNextEntry(new ZipEntry("challenge.xml"));
        XMLUtils.writeXML(_challengeDocument, writer, Utilities.DEFAULT_CHARSET.name());
        zipOut.closeEntry();
        zipOut.putNextEntry(new ZipEntry("score.xml"));
        XMLUtils.writeXML(_scoreDocument, writer, Utilities.DEFAULT_CHARSET.name());
        zipOut.closeEntry();

        zipOut.close();
    }
}

From source file:ZipImploder.java

public void processDir(ZipOutputStream zos, File dir) throws IOException {
    String path = dir.getCanonicalPath();
    path = path.replace('\\', '/');
    if (includeDirs) {
        if (baseDir == null || path.length() > baseDir.length()) {
            String xpath = removeDrive(removeLead(path));
            if (xpath.length() > 0) {
                xpath += '/';
                ZipEntry ze = new ZipEntry(xpath);
                zos.putNextEntry(ze);
            }//from  ww w. j ava2 s. c  om
        }
    }
    dirCount++;
    String[] files = dir.list();
    for (int i = 0; i < files.length; i++) {
        String file = files[i];
        File f = new File(dir, file);
        if (f.isDirectory()) {
            processDir(zos, f);
        } else {
            processFile(zos, f);
        }
    }
}

From source file:de.mpg.escidoc.services.exportmanager.Export.java

/**
 * Write License Agreement file to the archive OutputStream
 * //  w  w w. jav a 2  s .  c o m
 * @param af
 *            is Archive Format
 * @param os
 *            - archive OutputStream
 * @throws IOException
 * @throws ExportManagerException
 */
private void addLicenseAgreement(File license, OutputStream os) throws IOException, ExportManagerException {

    if (license != null) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(license));
        if (os instanceof TarOutputStream) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(baos);
            writeFromStreamToStream(bis, baos);
            bis.close();
            byte[] file = baos.toByteArray();
            bos.close();
            TarEntry te = new TarEntry(license.getName());
            te.setSize(file.length);
            TarOutputStream tos = (TarOutputStream) os;
            tos.putNextEntry(te);
            tos.write(file);
            tos.closeEntry();
        } else if (os instanceof ZipOutputStream) {
            ZipEntry ze = new ZipEntry(license.getName());
            ZipOutputStream zos = (ZipOutputStream) os;
            zos.putNextEntry(ze);
            writeFromStreamToStream(bis, zos);
            bis.close();
            zos.closeEntry();
        } else {
            throw new ExportManagerException("Wrong archive OutputStream: " + os);
        }
    }
}

From source file:edu.harvard.med.screensaver.service.cherrypicks.CherryPickRequestPlateMapFilesBuilder.java

@SuppressWarnings("unchecked")
private InputStream doBuildZip(CherryPickRequest cherryPickRequest, Set<CherryPickAssayPlate> forPlates)
        throws IOException {
    ByteArrayOutputStream zipOutRaw = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(zipOutRaw);
    MultiMap/*<String,SortedSet<CherryPick>>*/ files2CherryPicks = buildCherryPickFiles(cherryPickRequest,
            forPlates);/*from  w ww  . j av  a 2  s .c o  m*/
    buildReadme(cherryPickRequest, zipOut);
    buildDistinctPlateCopyFile(cherryPickRequest, forPlates, zipOut);
    PrintWriter out = new CSVPrintWriter(new OutputStreamWriter(zipOut), NEWLINE);
    for (Iterator iter = files2CherryPicks.keySet().iterator(); iter.hasNext();) {
        String fileName = (String) iter.next();
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOut.putNextEntry(zipEntry);
        writeHeadersRow(out);
        for (LabCherryPick cherryPick : (SortedSet<LabCherryPick>) files2CherryPicks.get(fileName)) {
            writeCherryPickRow(out, cherryPick);
        }
        out.flush();
    }
    out.close();
    return new ByteArrayInputStream(zipOutRaw.toByteArray());
}

From source file:com.eviware.soapui.integration.exporter.ProjectExporter.java

/**
 * Compress temporary directory and save it on given path.
 * //from ww  w . ja va 2 s. c o m
 * @param exportPath
 * @return
 * @throws IOException
 */
private boolean packageAll(String exportPath) {
    if (!exportPath.endsWith(".zip"))
        exportPath = exportPath + ".zip";

    BufferedInputStream origin = null;
    ZipOutputStream out;
    boolean result = true;
    try {
        FileOutputStream dest = new FileOutputStream(exportPath);
        out = new ZipOutputStream(new BufferedOutputStream(dest));
        byte data[] = new byte[BUFFER];
        // get a list of files from current directory

        String files[] = tmpDir.list();

        for (int i = 0; i < files.length; i++) {
            //            System.out.println( "Adding: " + files[i] );
            FileInputStream fi = new FileInputStream(new File(tmpDir, files[i]));
            origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(files[i]);
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }
        out.close();
    } catch (IOException e) {
        // TODO: handle exception
        result = false;
    }
    return result;
}

From source file:de.bps.onyx.plugin.OnyxExportManager.java

public void exportResults(List<QTIResultSet> resultSets, ZipOutputStream exportStream,
        CourseNode currentCourseNode) {//  www  .  ja va2 s. c o m
    final String path = createTargetFilename(currentCourseNode.getShortTitle(), "TEST");
    for (final QTIResultSet rs : resultSets) {
        String resultXml = getResultXml(rs.getIdentity().getName(),
                currentCourseNode.getModuleConfiguration().get(IQEditController.CONFIG_KEY_TYPE).toString(),
                currentCourseNode.getIdent(), rs.getAssessmentID());

        String filename = path + "/" + rs.getIdentity().getName() + "_" + rs.getCreationDate() + ".xml";
        try {
            exportStream.putNextEntry(new ZipEntry(filename));
            IOUtils.write(resultXml, exportStream);
            exportStream.closeEntry();
        } catch (IOException e) {
            log.error("", e);
        }
    }
}

From source file:abfab3d.shapejs.Project.java

public void save(String file) throws IOException {
    EvaluatedScript escript = m_script.getEvaluatedScript();
    Map<String, Parameter> scriptParams = escript.getParamMap();
    Gson gson = JSONParsing.getJSONParser();

    String code = escript.getCode();

    Path workingDirName = Files.createTempDirectory("saveScript");
    String workingDirPath = workingDirName.toAbsolutePath().toString();
    Map<String, Object> params = new HashMap<String, Object>();

    // Write the script to file
    File scriptFile = new File(workingDirPath + "/main.js");
    FileUtils.writeStringToFile(scriptFile, code, "UTF-8");

    // Loop through params and create key/pair entries
    for (Map.Entry<String, Parameter> entry : scriptParams.entrySet()) {
        String name = entry.getKey();
        Parameter pval = entry.getValue();

        if (pval.isDefaultValue())
            continue;

        ParameterType type = pval.getType();

        switch (type) {
        case URI:
            URIParameter urip = (URIParameter) pval;
            String u = (String) urip.getValue();

            //                   System.out.println("*** uri: " + u);
            File f = new File(u);

            String fileName = null;

            // TODO: This is hacky. If the parameter value is a directory, then assume it was
            //       originally a zip file, and its contents were extracted in the directory.
            //       Search for the zip file in the directory and copy that to the working dir.
            if (f.isDirectory()) {
                File[] files = f.listFiles();
                for (int i = 0; i < files.length; i++) {
                    String fname = files[i].getName();
                    if (fname.endsWith(".zip")) {
                        fileName = fname;
                        f = files[i];//w  w w  .j  a v a 2  s.c  o  m
                    }
                }
            } else {
                fileName = f.getName();
            }

            params.put(name, fileName);

            // Copy the file to working directory
            FileUtils.copyFile(f, new File(workingDirPath + "/" + fileName), true);
            break;
        case LOCATION:
            LocationParameter lp = (LocationParameter) pval;
            Vector3d p = lp.getPoint();
            Vector3d n = lp.getNormal();
            double[] point = { p.x, p.y, p.z };
            double[] normal = { n.x, n.y, n.z };
            //                   System.out.println("*** lp: " + java.util.Arrays.toString(point) + ", " + java.util.Arrays.toString(normal));
            Map<String, double[]> loc = new HashMap<String, double[]>();
            loc.put("point", point);
            loc.put("normal", normal);
            params.put(name, loc);
            break;
        case AXIS_ANGLE_4D:
            AxisAngle4dParameter aap = (AxisAngle4dParameter) pval;
            AxisAngle4d a = (AxisAngle4d) aap.getValue();
            params.put(name, a);
            break;
        case DOUBLE:
            DoubleParameter dp = (DoubleParameter) pval;
            Double d = (Double) dp.getValue();
            //                   System.out.println("*** double: " + d);

            params.put(name, d);
            break;
        case INTEGER:
            IntParameter ip = (IntParameter) pval;
            Integer i = ip.getValue();
            //                   System.out.println("*** int: " + pval);
            params.put(name, i);
            break;
        case STRING:
            StringParameter sp = (StringParameter) pval;
            String s = sp.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, s);
            break;
        case COLOR:
            ColorParameter cp = (ColorParameter) pval;
            Color c = cp.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, c.toHEX());
            break;
        case ENUM:
            EnumParameter ep = (EnumParameter) pval;
            String e = ep.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, e);
            break;
        default:
            params.put(name, pval);
        }

    }

    if (params.size() > 0) {
        String paramsJson = gson.toJson(params);
        File paramFile = new File(workingDirPath + "/" + "params.json");
        FileUtils.writeStringToFile(paramFile, paramsJson, "UTF-8");
    }

    File[] files = (new File(workingDirPath)).listFiles();

    FileOutputStream fos = new FileOutputStream(file);
    ZipOutputStream zos = new ZipOutputStream(fos);
    System.out.println("*** Num files to zip: " + files.length);

    try {
        byte[] buffer = new byte[1024];

        for (int i = 0; i < files.length; i++) {
            //                if (files[i].getName().endsWith(".zip")) continue;

            System.out.println("*** Adding file: " + files[i].getName());
            FileInputStream fis = new FileInputStream(files[i]);
            ZipEntry ze = new ZipEntry(files[i].getName());
            zos.putNextEntry(ze);

            int len;
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            fis.close();
        }
    } finally {
        zos.closeEntry();
        zos.close();
    }
}

From source file:edu.mit.lib.bagit.Filler.java

private void fillZip(File dirFile, String relBase, ZipOutputStream zout) throws IOException {
    for (File file : dirFile.listFiles()) {
        String relPath = relBase + File.separator + file.getName();
        if (file.isDirectory()) {
            fillZip(file, relPath, zout);
        } else {//  ww  w . j  a  va  2 s  .c  om
            ZipEntry entry = new ZipEntry(relPath);
            entry.setTime(0L);
            zout.putNextEntry(entry);
            Files.copy(file.toPath(), zout);
            zout.closeEntry();
        }
    }
}