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:com.glanznig.beepme.data.DataExporter.java

private String zipFiles(File zipFile, List<File> fileList) {
    String path = null;/* w  w  w .j  a  v  a  2 s .  c o  m*/

    if (zipFile != null && fileList != null) {
        try {
            BufferedInputStream bufIn = null;
            FileOutputStream zipFOutStream = new FileOutputStream(zipFile);
            ZipOutputStream outStream = new ZipOutputStream(new BufferedOutputStream(zipFOutStream));

            byte data[] = new byte[BUFFER];
            Iterator<File> i = fileList.iterator();

            while (i.hasNext()) {
                File f = i.next();
                FileInputStream fIn = new FileInputStream(f);
                bufIn = new BufferedInputStream(fIn, BUFFER);
                ZipEntry entry = new ZipEntry(f.getName());
                outStream.putNextEntry(entry);
                int count;
                while ((count = bufIn.read(data, 0, BUFFER)) != -1) {
                    outStream.write(data, 0, count);
                }
                bufIn.close();
            }
            outStream.close();

            path = zipFile.getAbsolutePath();

        } catch (Exception e) {
            Log.e(TAG, "error while zipping.", e);
        }
    }

    return path;
}

From source file:edu.isi.wings.catalog.component.api.impl.oodt.ComponentCreationFM.java

private void addDirToArchive(ZipOutputStream zos, File srcFile) {
    File[] files = srcFile.listFiles();
    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            addDirToArchive(zos, files[i]);
            continue;
        }//www  . j ava2 s . com
        try {
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(files[i]);
            zos.putNextEntry(new ZipEntry(files[i].getName()));
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }
            zos.closeEntry();
            fis.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:com.headwire.aem.tooling.intellij.eclipse.stub.JarBuilder.java

private void zipDir(final IFolder sourceDir, final ZipOutputStream zos, final String path)
        throws CoreException, IOException {

    for (final IResource f : sourceDir.members()) {
        if (f.getType() == IResource.FOLDER) {
            final String prefix = path + f.getName() + "/";
            zos.putNextEntry(new ZipEntry(prefix));
            zipDir((IFolder) f, zos, prefix);
        } else if (f.getType() == IResource.FILE) {
            final String entry = path + f.getName();
            if (JarFile.MANIFEST_NAME.equals(entry)) {
                continue;
            }/*from w  ww  .j av  a 2s. co  m*/
            final InputStream fis = ((IFile) f).getContents();
            try {
                final byte[] readBuffer = new byte[8192];
                int bytesIn = 0;
                final ZipEntry anEntry = new ZipEntry(entry);
                zos.putNextEntry(anEntry);
                while ((bytesIn = fis.read(readBuffer)) != -1) {
                    zos.write(readBuffer, 0, bytesIn);
                }
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }
    }
}

From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java

/**
 * Creates MimeMessage with supplied values
 * /*www  .  j av a2 s . c  o  m*/
 * @param to - to email address
 * @param docType - String value for the attached document type
 * @param subject - Subject for the email
 * @param instructions - email body
 * @param content - content to be sent as attachment
 * @return MimeMessage instance
 */
public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content,
        String metadataXMl, String title, String indexBodyToken, String readmeToken) {
    final MimeMessage msg = mailSender.createMimeMessage();
    UUID uniqueID = UUID.randomUUID();
    tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID);
    try {
        msg.setFrom(new InternetAddress(getFrom()));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // The readable part
        final MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(instructions);
        mbp1.setHeader("Content-Type", "text/plain");

        // The notification
        final MimeBodyPart mbp2 = new MimeBodyPart();

        final String contentType = "application/xml; charset=UTF-8";

        String extension;

        // HL7 messages should be a txt file, otherwise xml
        if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) {
            extension = TXT_EXT;
        } else {
            extension = XML_EXT;
        }

        final String fileName = docType + UUID.randomUUID() + extension;

        //            final DataSource ds = new AttachmentDS(fileName, content, contentType);
        //            mbp2.setDataHandler(new DataHandler(ds));

        /******** START NHIN COMPLIANCE CHANGES *****/

        boolean isTempZipFolderCreated = tempZipFolder.mkdirs();
        if (!isTempZipFolderCreated) {
            LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
        }

        String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM"));
        String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT"));

        indexFileString = StringUtils.replace(indexFileString, "@document_title@", title);
        indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString);

        readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString);

        // move template files & replace tokens
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false);
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false);

        // create sub-directories
        String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01";
        File nhinSubDirectory = new File(nhinSubDirectoryPath);
        boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs();
        if (!isNhinSubDirectoryCreated) {
            LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
        }
        FileOutputStream metadataStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/METADATA.XML"));
        metadataStream.write(metadataXMl.getBytes());
        metadataStream.flush();
        metadataStream.close();
        FileOutputStream documentStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/DOCUMENT" + extension));
        documentStream.write(content.getBytes());
        documentStream.flush();
        documentStream.close();

        String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP";
        byte[] buffer = new byte[1024];
        //            FileOutputStream fos = new FileOutputStream(zipFile);
        //            ZipOutputStream zos = new ZipOutputStream(fos);

        List<String> fileList = generateFileList(tempZipFolder);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size());
        ZipOutputStream zos = new ZipOutputStream(bout);
        //            LOG.info("File List size: "+fileList.size());
        for (String file : fileList) {
            ZipEntry ze = new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
        // remember close it
        zos.close();

        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        mbp2.setDataHandler(new DataHandler(source));
        mbp2.setFileName(docType + ".ZIP");

        /******** END NHIN COMPLIANCE CHANGES *****/

        //            mbp2.setFileName(fileName);
        //            mbp2.setHeader("Content-Type", contentType);

        final Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        //            FileUtils.deleteDirectory(tempZipFolder);
    } catch (AddressException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (MessagingException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        throw new ApplicationRuntimeException(e.getMessage());
    } finally {
        //reset filelist contents
        fileList = new ArrayList<String>();
    }
    return msg;
}

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

private void zip_folder(File file, ZipOutputStream zout) throws IOException {
    byte[] data = new byte[BUFFER];
    int read;/*  w  ww  .jav a2s  .  c o  m*/

    if (file.isFile()) {
        ZipEntry entry = new ZipEntry(file.getName());
        zout.putNextEntry(entry);
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(file));

        while ((read = instream.read(data, 0, BUFFER)) != -1)
            zout.write(data, 0, read);

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

    } else if (file.isDirectory()) {
        String[] list = file.list();
        int len = list.length;

        for (int i = 0; i < len; i++)
            zip_folder(new File(file.getPath() + "/" + list[i]), zout);
    }
}

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];/*from   w w  w  . jav a  2  s. com*/
                    }
                }
            } 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:com.eviware.soapui.integration.exporter.ProjectExporter.java

/**
 * Compress temporary directory and save it on given path.
 * //from  w w  w  .  j ava2 s  .co  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:org.candlepin.sync.Exporter.java

private void addFileToArchive(ZipOutputStream out, int charsToDropFromName, File file)
        throws IOException, FileNotFoundException {
    log.debug("Adding file to archive: " + file.getAbsolutePath().substring(charsToDropFromName));
    out.putNextEntry(new ZipEntry(file.getAbsolutePath().substring(charsToDropFromName)));
    FileInputStream in = null;/*from  www. j  a v a  2 s  .co  m*/
    try {
        in = new FileInputStream(file);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.baasbox.db.async.ExportJob.java

@Override
public void run() {
    FileOutputStream dest = null;
    ZipOutputStream zip = null;
    FileOutputStream tempJsonOS = null;
    FileInputStream in = null;/*from  ww w  .j  av  a 2 s . c o m*/
    try {
        //File f = new File(this.fileName);
        File f = File.createTempFile("export", ".temp");

        dest = new FileOutputStream(f);
        zip = new ZipOutputStream(dest);

        File tmpJson = File.createTempFile("export", ".json");
        tempJsonOS = new FileOutputStream(tmpJson);
        DbHelper.exportData(this.appcode, tempJsonOS);
        BaasBoxLogger.info(String.format("Writing %d bytes ", tmpJson.length()));
        tempJsonOS.close();

        ZipEntry entry = new ZipEntry("export.json");
        zip.putNextEntry(entry);
        in = new FileInputStream(tmpJson);
        final int BUFFER = BBConfiguration.getImportExportBufferSize();
        byte buffer[] = new byte[BUFFER];

        int length;
        while ((length = in.read(buffer)) > 0) {
            zip.write(buffer, 0, length);
        }
        zip.closeEntry();
        in.close();

        File manifest = File.createTempFile("manifest", ".txt");
        FileUtils.writeStringToFile(manifest,
                BBInternalConstants.IMPORT_MANIFEST_VERSION_PREFIX + BBConfiguration.getApiVersion());

        ZipEntry entryManifest = new ZipEntry("manifest.txt");
        zip.putNextEntry(entryManifest);
        zip.write(FileUtils.readFileToByteArray(manifest));
        zip.closeEntry();

        tmpJson.delete();
        manifest.delete();

        File finaldestination = new File(this.fileName);
        FileUtils.moveFile(f, finaldestination);

    } catch (Exception e) {
        BaasBoxLogger.error(ExceptionUtils.getMessage(e));
    } finally {
        try {
            if (zip != null)
                zip.close();
            if (dest != null)
                dest.close();
            if (tempJsonOS != null)
                tempJsonOS.close();
            if (in != null)
                in.close();

        } catch (Exception ioe) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(ioe));
        }
    }
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

/**
 * 2jar?,??jar/*from  w  w w  .  ja  va  2 s  .c  o m*/
 * @param baseJar
 * @param diffJar
 * @param outJar
 */
public static void unionJar(File baseJar, File diffJar, File outJar) throws IOException {
    File outParentFolder = outJar.getParentFile();
    if (!outParentFolder.exists()) {
        outParentFolder.mkdirs();
    }
    List<String> diffEntries = getZipEntries(diffJar);
    FileOutputStream fos = new FileOutputStream(outJar);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(baseJar);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (diffEntries.contains(name)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();

}