Example usage for java.util.zip ZipOutputStream flush

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the compressed output stream.

Usage

From source file:org.apache.brooklyn.rest.resources.BundleAndTypeResourcesTest.java

private static File createZip(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "zip");

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

    for (Map.Entry<String, String> entry : files.entrySet()) {
        ZipEntry ze = new ZipEntry(entry.getKey());
        zip.putNextEntry(ze);//w w  w .ja v a2s .c o  m
        zip.write(entry.getValue().getBytes());
    }

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}

From source file:org.agnitas.util.ZipUtilities.java

/**
 * Add data to an open ZipOutputStream as a virtual file
 * /*from   w  ww. ja  v a 2 s . c  om*/
 * @param fileData
 * @param relativeDirPath
 * @param filename
 * @param destinationZipFileSream
 * @throws IOException
 */
public static void addFileDataToOpenZipFileStream(byte[] fileData, String relativeDirPath, String filename,
        ZipOutputStream destinationZipFileSream) throws IOException {
    if (fileData == null)
        throw new IOException("FileData is missing");

    if (StringUtils.isEmpty(filename) || filename.trim().length() == 0)
        throw new IOException("Filename is missing");

    if (destinationZipFileSream == null)
        throw new IOException("DestinationStream is not ready");

    if (relativeDirPath == null || (!relativeDirPath.endsWith("/") && !relativeDirPath.endsWith("\\")))
        throw new IOException("RelativeDirPath is invalid");

    ZipEntry entry = new ZipEntry(relativeDirPath + filename);
    entry.setTime(new Date().getTime());
    destinationZipFileSream.putNextEntry(entry);

    destinationZipFileSream.write(fileData);

    destinationZipFileSream.flush();
    destinationZipFileSream.closeEntry();
}

From source file:org.geoserver.wfs.response.SpatiaLiteOutputFormat.java

@Override
protected void write(FeatureCollectionResponse featureCollection, OutputStream output, Operation getFeature)
        throws IOException, ServiceException {

    SpatiaLiteDataStoreFactory dsFactory = new SpatiaLiteDataStoreFactory();
    if (!dsFactory.isAvailable()) {
        throw new ServiceException(
                "SpatiaLite support not avaialable, ensure all required " + "native libraries are installed");
    }//from w  ww  .j  a v a  2s .co m

    /**
     * base location to temporally store spatialite database `es
     */
    File dbFile = File.createTempFile("spatialite", ".db");

    Map dbParams = new HashMap();
    dbParams.put(SpatiaLiteDataStoreFactory.DBTYPE.key, "spatialite");
    dbParams.put(SpatiaLiteDataStoreFactory.DATABASE.key, dbFile.getAbsolutePath());

    DataStore dataStore = dsFactory.createDataStore(dbParams);
    try {
        for (FeatureCollection fc : featureCollection.getFeatures()) {

            SimpleFeatureType featureType = (SimpleFeatureType) fc.getSchema();
            //create a feature type
            dataStore.createSchema(featureType);

            FeatureWriter fw = dataStore.getFeatureWriterAppend(featureType.getTypeName(),
                    Transaction.AUTO_COMMIT);

            //Start populating the table: tbl_name.
            SimpleFeatureIterator it = (SimpleFeatureIterator) fc.features();
            while (it.hasNext()) {
                SimpleFeature f = it.next();
                SimpleFeature g = (SimpleFeature) fw.next();

                for (AttributeDescriptor att : f.getFeatureType().getAttributeDescriptors()) {
                    String attName = att.getLocalName();
                    g.setAttribute(attName, f.getAttribute(attName));
                }
                fw.write();
            }
        }
    } finally {
        dataStore.dispose();
    }

    BufferedInputStream bin = new BufferedInputStream(new FileInputStream(dbFile));

    ZipOutputStream zout = new ZipOutputStream(output);
    zout.putNextEntry(new ZipEntry(getDbFileName(getFeature)));

    IOUtils.copy(bin, zout);
    zout.flush();
    zout.closeEntry();

    dbFile.delete();
}

From source file:eionet.gdem.utils.ZipUtil.java

/**
 *
 * @param f/*  ww w. j  a v  a2  s  .c  o  m*/
 *            - File that will be zipped
 * @param outZip
 *            - ZipOutputStream represents the zip file, where the files will be placed
 * @param sourceDir
 *            - root directory, where the zipping started
 * @param doCompress
 *            - don't comress the file, if doCompress=true
 * @throws IOException If an error occurs.
 */
public static void zipFile(File f, ZipOutputStream outZip, String sourceDir, boolean doCompress)
        throws IOException {

    // Read the source file into byte array
    byte[] fileBytes = Utils.getBytesFromFile(f);

    // create a new zip entry
    String strAbsPath = f.getPath();
    String strZipEntryName = strAbsPath.substring(sourceDir.length() + 1, strAbsPath.length());
    strZipEntryName = Utils.Replace(strZipEntryName, File.separator, "/");
    ZipEntry anEntry = new ZipEntry(strZipEntryName);

    // Don't compress the file, if not needed
    if (!doCompress) {
        // ZipEntry can't calculate crc size automatically, if we use STORED method.
        anEntry.setMethod(ZipEntry.STORED);
        anEntry.setSize(fileBytes.length);
        CRC32 crc321 = new CRC32();
        crc321.update(fileBytes);
        anEntry.setCrc(crc321.getValue());
    }
    // place the zip entry in the ZipOutputStream object
    outZip.putNextEntry(anEntry);

    // now write the content of the file to the ZipOutputStream
    outZip.write(fileBytes);

    outZip.flush();
    // Close the current entry
    outZip.closeEntry();

}

From source file:org.romaframework.core.util.FileUtils.java

/**
 * Method that create a compressed archive from a List of files.
 * /*from w w  w  .  j  a v  a 2 s.  co m*/
 * @param attachments
 *          - The list of file to compress
 * @param iFileName
 *          - The name of the compressed file
 * @return the compressed File generated.
 * @throws IOException
 * @see File
 */
public static File compressAttachments(String iFileName, List<File> attachments) throws IOException {
    File fileToSave = new File(iFileName + ".zip");
    // definiamo l'output previsto che sar un file in formato zip
    ZipOutputStream out = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(fileToSave), BUFFER));
    try {
        for (File attachment : attachments) {

            // definiamo il buffer per lo stream di bytes
            byte[] data = new byte[1000];

            // indichiamo il nome del file che subir la compressione
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(attachment), BUFFER);
            int count;

            // processo di compressione
            out.putNextEntry(new ZipEntry(getFileNameWithoutSessionId(attachment.getName())));
            while ((count = in.read(data, 0, 1000)) != -1) {
                out.write(data, 0, count);
            }
            out.closeEntry();
            in.close();
        }
    } finally {
        out.flush();
        out.close();
    }
    fileToSave.deleteOnExit();
    return fileToSave;
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ?//from   w w  w .  ja v a2s  .com
 * 
 * @param files 
 * @param out ?
 * @throws java.io.IOException
 * @throws Exception
 */
public static void zipDownLoad(File file, HttpServletResponse response) throws IOException {

    ServletOutputStream out = response.getOutputStream();
    ZipOutputStream zipout = new ZipOutputStream(out);

    zipout.setLevel(1);
    // zipout.setEncoding("GBK");
    for (File f : file.listFiles()) {
        if (f.isFile()) {
            compressFile(f, f.getName(), zipout, "");
        } else {
            compressFolder(f, f.getName(), zipout, "");
        }
    }

    zipout.finish();
    zipout.flush();
}

From source file:org.apache.parquet.tools.submit.FileFormat.java

public void zipFolder(String srcFolder, String destZipFile) throws Exception {
    ZipOutputStream zip = null;
    FileOutputStream fileWriter = null;
    fileWriter = new FileOutputStream(destZipFile);
    zip = new ZipOutputStream(fileWriter);
    addFolderToZip("", srcFolder, zip);
    zip.flush();
    zip.close();/*from   w  w  w  .ja va 2 s.c o m*/
}

From source file:org.olat.core.util.ZipUtil.java

public static boolean zip(List<VFSItem> vfsFiles, VFSLeaf target, boolean compress) {
    boolean success = true;

    String zname = target.getName();
    if (target instanceof LocalImpl) {
        zname = ((LocalImpl) target).getBasefile().getAbsolutePath();
    }//  w w  w .  j  a  v  a  2s .c  o  m

    OutputStream out = target.getOutputStream(false);

    if (out == null) {
        throw new OLATRuntimeException(ZipUtil.class, "Error getting output stream for file: " + zname, null);
    }

    long s = System.currentTimeMillis();

    ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(out, FileUtils.BSIZE));

    if (vfsFiles.size() == 0) {
        try {
            zipOut.close();
        } catch (IOException e) {
            //
        }
        return true;
    }

    zipOut.setLevel(compress ? 9 : 0);
    for (Iterator<VFSItem> iter = vfsFiles.iterator(); success && iter.hasNext();) {
        success = addToZip(iter.next(), "", zipOut);
    }

    try {
        zipOut.flush();
        zipOut.close();
        log.info("zipped (" + (compress ? "compress" : "store") + ") " + zname + " t="
                + Long.toString(System.currentTimeMillis() - s));
    } catch (IOException e) {
        throw new OLATRuntimeException(ZipUtil.class, "I/O error closing file: " + zname, null);
    }

    return success;
}

From source file:com.commonsware.android.backup.BackupService.java

private File buildBackup() throws IOException {
    File zipFile = new File(getCacheDir(), BACKUP_FILENAME);

    if (zipFile.exists()) {
        zipFile.delete();/*  w  w  w  .  j  a v a 2 s .  co  m*/
    }

    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    zipDir(ZIP_PREFIX_FILES, getFilesDir(), zos);
    zipDir(ZIP_PREFIX_PREFS, getSharedPrefsDir(this), zos);
    zipDir(ZIP_PREFIX_EXTERNAL, getExternalFilesDir(null), zos);
    zos.flush();
    fos.getFD().sync();
    zos.close();

    return (zipFile);
}

From source file:it.geosolutions.tools.compress.file.Compressor.java

public static File deflate(final File outputDir, final File zipFile, final File[] files, boolean overwrite) {

    if (zipFile.exists() && overwrite) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("The output file already exists: " + zipFile + " overvriting");
        return zipFile;
    }/*from   www . j  a  v a2  s . c o m*/

    // Create a buffer for reading the files
    byte[] buf = new byte[Conf.getBufferSize()];

    ZipOutputStream out = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(zipFile);
        bos = new BufferedOutputStream(fos);
        out = new ZipOutputStream(bos);

        // Compress the files
        for (File file : files) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                if (file.isDirectory()) {
                    continue;
                } else {
                    // Add ZIP entry to output stream.
                    out.putNextEntry(new ZipEntry(file.getName()));
                    // Transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.flush();
                }

            } finally {
                try {
                    // Complete the entry
                    out.closeEntry();
                } catch (Exception e) {
                }
                IOUtils.closeQuietly(in);
            }

        }

    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
        return null;
    } finally {

        // Complete the ZIP file
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(bos);
        IOUtils.closeQuietly(fos);
    }

    return zipFile;
}