Example usage for java.util.zip ZipOutputStream ZipOutputStream

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

Introduction

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

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:net.sourceforge.floggy.maven.ZipUtils.java

/**
 * DOCUMENT ME!/*from w ww  .  j  a v a 2 s . c  o  m*/
*
* @param directories DOCUMENT ME!
* @param output DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
*/
public static void zip(File[] directories, File output) throws IOException {
    FileInputStream in = null;
    ZipOutputStream out = null;
    ZipEntry entry = null;

    Collection allFiles = new LinkedList();

    for (int i = 0; i < directories.length; i++) {
        allFiles.addAll(FileUtils.listFiles(directories[i], null, true));
    }

    out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(output)));

    for (Iterator iter = allFiles.iterator(); iter.hasNext();) {
        File temp = (File) iter.next();
        String name = getEntryName(directories, temp.getAbsolutePath());
        entry = new ZipEntry(name);
        out.putNextEntry(entry);

        if (!temp.isDirectory()) {
            in = new FileInputStream(temp);
            IOUtils.copy(in, out);
            in.close();
        }
    }

    out.close();
}

From source file:com.isomorphic.maven.util.ArchiveUtils.java

/**
 * Builds a ZIP file from the contents of a directory on the filesystem (recursively).
 * //from w w w.ja v  a2  s  . c o m
 * @see http://stackoverflow.com/questions/1281229/how-to-use-jaroutputstream-to-create-a-jar-file
 * 
 * @param directory the directory containing the content to be xzipped up
 * @param output the zip file to be written to
 * @throws IOException
 */
public static void zip(File directory, File output) throws IOException {
    output.getParentFile().mkdirs();
    ZipOutputStream target = new ZipOutputStream(new FileOutputStream(output));
    zip(directory, directory, target);
    target.close();
}

From source file:ml.shifu.shifu.util.IndependentTreeModelUtils.java

public boolean convertBinaryToZipSpec(File treeModelFile, File outputZipFile) {
    FileInputStream treeModelInputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {/*  w w w .  ja  v  a 2s .c  o m*/
        treeModelInputStream = new FileInputStream(treeModelFile);
        IndependentTreeModel treeModel = IndependentTreeModel.loadFromStream(treeModelInputStream);
        List<List<TreeNode>> trees = treeModel.getTrees();
        treeModel.setTrees(null);
        if (CollectionUtils.isEmpty(trees)) {
            logger.error("No trees found in the tree model.");
            return false;
        }

        zipOutputStream = new ZipOutputStream(new FileOutputStream(outputZipFile));

        ZipEntry modelEntry = new ZipEntry(MODEL_CONF);
        zipOutputStream.putNextEntry(modelEntry);
        ByteArrayOutputStream byos = new ByteArrayOutputStream();
        JSONUtils.writeValue(new OutputStreamWriter(byos), treeModel);
        zipOutputStream.write(byos.toByteArray());
        IOUtils.closeQuietly(byos);

        ZipEntry treesEntry = new ZipEntry(MODEL_TREES);
        zipOutputStream.putNextEntry(treesEntry);
        DataOutputStream dataOutputStream = new DataOutputStream(zipOutputStream);
        dataOutputStream.writeInt(trees.size());
        for (List<TreeNode> forest : trees) {
            dataOutputStream.writeInt(forest.size());
            for (TreeNode treeNode : forest) {
                treeNode.write(dataOutputStream);
            }
        }
        IOUtils.closeQuietly(dataOutputStream);
    } catch (IOException e) {
        logger.error("Error occurred when convert the tree model to zip format.", e);
        return false;
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(treeModelInputStream);
    }

    return true;
}

From source file:com.l2jfree.gameserver.util.DatabaseBackupManager.java

public static void makeBackup() {
    File f = new File(Config.DATAPACK_ROOT, Config.DATABASE_BACKUP_SAVE_PATH);
    if (!f.mkdirs() && !f.exists()) {
        _log.warn("Could not create folder " + f.getAbsolutePath());
        return;//w  w  w .ja  v  a2  s . com
    }

    _log.info("DatabaseBackupManager: backing up `" + Config.DATABASE_BACKUP_DATABASE_NAME + "`...");

    Process run = null;
    try {
        run = Runtime.getRuntime().exec("mysqldump" + " --user=" + Config.DATABASE_LOGIN + " --password="
                + Config.DATABASE_PASSWORD
                + " --compact --complete-insert --default-character-set=utf8 --extended-insert --lock-tables --quick --skip-triggers "
                + Config.DATABASE_BACKUP_DATABASE_NAME, null, new File(Config.DATABASE_BACKUP_MYSQLDUMP_PATH));
    } catch (Exception e) {
    } finally {
        if (run == null) {
            _log.warn("Could not execute mysqldump!");
            return;
        }
    }

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        Date time = new Date();

        File bf = new File(f, sdf.format(time) + (Config.DATABASE_BACKUP_COMPRESSION ? ".zip" : ".sql"));
        if (!bf.createNewFile())
            throw new IOException("Cannot create backup file: " + bf.getCanonicalPath());
        InputStream input = run.getInputStream();
        OutputStream out = new FileOutputStream(bf);
        if (Config.DATABASE_BACKUP_COMPRESSION) {
            ZipOutputStream dflt = new ZipOutputStream(out);
            dflt.setMethod(ZipOutputStream.DEFLATED);
            dflt.setLevel(Deflater.BEST_COMPRESSION);
            dflt.setComment("L2JFree Schema Backup Utility\r\n\r\nBackup date: "
                    + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS z").format(time));
            dflt.putNextEntry(new ZipEntry(Config.DATABASE_BACKUP_DATABASE_NAME + ".sql"));
            out = dflt;
        }

        byte[] buf = new byte[4096];
        int written = 0;
        for (int read; (read = input.read(buf)) != -1;) {
            out.write(buf, 0, read);

            written += read;
        }
        input.close();
        out.close();

        if (written == 0) {
            bf.delete();
            BufferedReader br = new BufferedReader(new InputStreamReader(run.getErrorStream()));
            String line;
            while ((line = br.readLine()) != null)
                _log.warn("DatabaseBackupManager: " + line);
            br.close();
        } else
            _log.info("DatabaseBackupManager: Schema `" + Config.DATABASE_BACKUP_DATABASE_NAME
                    + "` backed up successfully in " + (System.currentTimeMillis() - time.getTime()) / 1000
                    + " s.");

        run.waitFor();
    } catch (Exception e) {
        _log.warn("DatabaseBackupManager: Could not make backup: ", e);
    }
}

From source file:it.geosolutions.mariss.wps.ppio.OutputResourcesPPIO.java

@Override
public void encode(Object value, OutputStream os) throws Exception {

    ZipOutputStream zos = null;/*from  w  w w  .j av a  2s.  c o m*/
    try {
        OutputResource or = (OutputResource) value;

        zos = new ZipOutputStream(os);
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);

        Iterator<File> iter = or.getDeletableResourcesIterator();
        while (iter.hasNext()) {

            File tmp = iter.next();
            if (!tmp.exists() || !tmp.canRead() || !tmp.canWrite()) {
                LOGGER.warning("Skip Deletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

            if (!tmp.delete()) {
                LOGGER.warning("File '" + tmp.getName() + "' cannot be deleted...");
            }
        }
        iter = null;

        Iterator<File> iter2 = or.getUndeletableResourcesIterator();
        while (iter2.hasNext()) {

            File tmp = iter2.next();
            if (!tmp.exists() || !tmp.canRead()) {
                LOGGER.warning("Skip Undeletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

        }
    } finally {
        try {
            zos.close();
        } catch (IOException e) {
            LOGGER.severe(e.getMessage());
        }
    }
}

From source file:com.migo.service.impl.SysGeneratorServiceImpl.java

@Override
public byte[] generatorCode(String[] tableNames) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(outputStream);

    for (String tableName : tableNames) {
        //?/*w  w w  . j  a  v  a 2 s .  c o  m*/
        Map<String, String> table = queryTable(tableName);
        //?
        List<Map<String, String>> columns = queryColumns(tableName);
        //??
        GenUtils.generatorCode(table, columns, zip);
    }
    IOUtils.closeQuietly(zip);
    return outputStream.toByteArray();
}

From source file:com.formkiq.core.util.Zips.java

/**
 * Create Zip file./* www .ja  v a 2s .c om*/
 * @param map {@link Map}
 * @return byte[] zip file
 * @throws IOException IOException
 */
public static byte[] zipFile(final Map<String, byte[]> map) throws IOException {

    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(bs);

    for (Map.Entry<String, byte[]> e : map.entrySet()) {

        String name = e.getKey();
        byte[] data = e.getValue();

        ZipEntry ze = new ZipEntry(name);
        zip.putNextEntry(ze);

        zip.write(data, 0, data.length);
        zip.closeEntry();
    }

    zip.finish();

    byte[] bytes = bs.toByteArray();

    IOUtils.closeQuietly(bs);
    IOUtils.closeQuietly(zip);

    return bytes;
}

From source file:com.google.mr4c.sources.LogsDatasetSource.java

public synchronized void copyToFinal() throws IOException {
    List<String> names = new ArrayList<String>(m_fileSrc.getAllFileNames());
    names.remove(ZIP_FILE_NAME);//from w  w w  .  j av a  2s  .  co m
    DataFileSink zipSink = m_fileSrc.getFileSink(ZIP_FILE_NAME);
    OutputStream output = zipSink.getFileOutputStream();
    try {
        ZipOutputStream zipStream = new ZipOutputStream(output);
        for (String name : names) {
            addZipEntry(zipStream, name);
        }
        zipStream.finish();
    } finally {
        output.close();
    }
}

From source file:de.pksoftware.springstrap.sapi.util.WebappZipper.java

public WebappZipper(OutputStream out, ServletContext servletContext) {
    zos = new ZipOutputStream(out);

    this.servletContext = servletContext;
}

From source file:gov.nih.nci.caarray.services.external.v1_0.data.JavaDataApiUtils.java

/**
 * {@inheritDoc}/*from   www  .  j a  v  a2  s . c  o  m*/
 */
public void copyFileContentsZipToOutputStream(Iterable<CaArrayEntityReference> fileRefs, OutputStream ostream)
        throws InvalidReferenceException, DataTransferException, IOException {
    ZipOutputStream zos = new ZipOutputStream(ostream);
    for (CaArrayEntityReference fileRef : fileRefs) {
        FileStreamableContents fsContents = dataService.streamFileContents(fileRef, true);
        zos.putNextEntry(new ZipEntry(fsContents.getMetadata().getName()));
        readFully(fsContents.getContentStream(), zos, true);
    }
    zos.finish();
}