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:com.espringtran.compressor4j.processor.Bzip2Processor.java

/**
 * Compress data// w ww . j a va2s. co m
 * 
 * @param fileCompressor
 *            FileCompressor object
 * @return
 * @throws Exception
 */
@Override
public byte[] compressData(FileCompressor fileCompressor) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BZip2CompressorOutputStream cos = new BZip2CompressorOutputStream(baos);
    ZipOutputStream zos = new ZipOutputStream(cos);
    try {
        zos.setLevel(fileCompressor.getLevel().getValue());
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setComment(fileCompressor.getComment());
        for (BinaryFile binaryFile : fileCompressor.getMapBinaryFile().values()) {
            zos.putNextEntry(new ZipEntry(binaryFile.getDesPath()));
            zos.write(binaryFile.getData());
            zos.closeEntry();
        }
        zos.flush();
        zos.finish();
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on compress data", e);
    } finally {
        zos.close();
        cos.close();
        baos.close();
    }
    return baos.toByteArray();
}

From source file:br.univali.celine.lms.utils.zip.Zip.java

public void zip(ArrayList<String> fileList, File destFile, int compressionLevel) throws Exception {

    if (destFile.exists())
        throw new Exception("File " + destFile.getName() + " already exists!!");

    int fileLength;
    byte[] buffer = new byte[4096];

    FileOutputStream fos = new FileOutputStream(destFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ZipOutputStream zipFile = new ZipOutputStream(bos);
    zipFile.setLevel(compressionLevel);//from   w  w  w.  j  a  v a  2s .co m

    for (int i = 0; i < fileList.size(); i++) {

        FileInputStream fis = new FileInputStream(fileList.get(i));
        BufferedInputStream bis = new BufferedInputStream(fis);
        ZipEntry ze = new ZipEntry(FilenameUtils.getName(fileList.get(i)));
        zipFile.putNextEntry(ze);

        while ((fileLength = bis.read(buffer, 0, 4096)) > 0)
            zipFile.write(buffer, 0, fileLength);

        zipFile.closeEntry();
        bis.close();
    }

    zipFile.close();

}

From source file:com.matze5800.paupdater.Functions.java

public static void addFilesToExistingZip(File zipFile, File[] files) throws IOException {
    File tempFile = new File(Environment.getExternalStorageDirectory() + "/pa_updater", "temp_kernel.zip");
    tempFile.delete();//from ww w.j  a v  a 2s .  c o  m

    boolean renameOk = zipFile.renameTo(tempFile);
    if (!renameOk) {
        throw new RuntimeException(
                "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }
    byte[] buf = new byte[1024];

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : files) {
            if (f.getName().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {

            out.putNextEntry(new ZipEntry(name));

            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    zin.close();

    for (int i = 0; i < files.length; i++) {
        InputStream in = new FileInputStream(files[i]);
        out.putNextEntry(new ZipEntry(files[i].getName()));

        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
    out.close();
    tempFile.delete();
}

From source file:net.sf.jabref.exporter.OpenDocumentSpreadsheetCreator.java

private static void storeOpenDocumentSpreadsheetFile(File file, InputStream source) throws Exception {

    try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) {

        //addResourceFile("mimetype", "/resource/ods/mimetype", out);
        ZipEntry ze = new ZipEntry("mimetype");
        String mime = "application/vnd.oasis.opendocument.spreadsheet";
        ze.setMethod(ZipEntry.STORED);
        ze.setSize(mime.length());/*  www .  ja  v a  2  s  . c om*/
        CRC32 crc = new CRC32();
        crc.update(mime.getBytes());
        ze.setCrc(crc.getValue());
        out.putNextEntry(ze);
        for (int i = 0; i < mime.length(); i++) {
            out.write(mime.charAt(i));
        }
        out.closeEntry();

        ZipEntry zipEntry = new ZipEntry("content.xml");
        //zipEntry.setMethod(ZipEntry.DEFLATED);
        out.putNextEntry(zipEntry);
        int c;
        while ((c = source.read()) >= 0) {
            out.write(c);
        }
        out.closeEntry();

        // Add manifest (required for OOo 2.0) and "meta.xml": These are in the
        // resource/ods directory, and are copied verbatim into the zip file.
        OpenDocumentSpreadsheetCreator.addResourceFile("meta.xml", "/resource/ods/meta.xml", out);

        OpenDocumentSpreadsheetCreator.addResourceFile("META-INF/manifest.xml", "/resource/ods/manifest.xml",
                out);
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.util.ArchiveCompressorZipImpl.java

/**
 * Compress the given files into an archive with the given name, plus the file extension.  Put the compressed
 * archive into the given directory./*from   www.  j a v  a 2s  .c o m*/
 *
 * @param files                the files to include in the archive
 * @param archiveName          the name of the archive, minus extension
 * @param destinationDirectory the location to put the new compressed archive
 * @param compress              flag to compress the archive
 * @return the File representing the created compressed archive
 * @throws IOException if it needs to
 */
public File createArchive(final List<File> files, final String archiveName, final File destinationDirectory,
        final Boolean compress) throws IOException {
    final File archiveFile = new File(destinationDirectory, archiveName + ZIP_EXTENSION);

    ZipOutputStream out = null;
    FileInputStream in = null;

    try {
        //noinspection IOResourceOpenedButNotSafelyClosed
        out = new ZipOutputStream(new FileOutputStream(archiveFile));
        final byte[] buf = new byte[1024];
        for (final File file : files) {
            try {
                //noinspection IOResourceOpenedButNotSafelyClosed
                in = new FileInputStream(file);
                out.putNextEntry(new ZipEntry(archiveName + File.separator + file.getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } finally {
        IOUtils.closeQuietly(out);
    }
    return archiveFile;
}

From source file:ZipTransformTest.java

public void testByteArrayTransformer() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file1 = File.createTempFile("temp", null);
    File file2 = File.createTempFile("temp", null);
    try {/*w ww.ja  v a 2  s.  c  o  m*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        ZipUtil.transformEntry(file1, name, new ByteArrayZipEntryTransformer() {
            protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException {
                String s = new String(input);
                assertEquals(new String(contents), s);
                return s.toUpperCase().getBytes();
            }
        }, file2);

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file2, name);
        assertNotNull(actual);
        assertEquals(new String(contents).toUpperCase(), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
        FileUtils.deleteQuietly(file2);
    }
}

From source file:Zip.java

/**
 * Create a OutputStream on a given file, transparently compressing the data
 * to a Zip file whose name is the provided file path, with a ".zip"
 * extension added./*from   w w w . j av a 2  s  . c  o  m*/
 *
 * @param file the file (with no zip extension)
 *
 * @return a OutputStream on the zip entry
 */
public static OutputStream createOutputStream(File file) {
    try {
        String path = file.getCanonicalPath();
        FileOutputStream fos = new FileOutputStream(path + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze = new ZipEntry(file.getName());
        zos.putNextEntry(ze);

        return zos;
    } catch (FileNotFoundException ex) {
        System.err.println(ex.toString());
        System.err.println(file + " not found");
    } catch (Exception ex) {
        System.err.println(ex.toString());
    }

    return null;
}

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

/**
 * ?????1????/*from  w  ww  . j a v  a2 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:com.baasbox.util.Util.java

public static void createZipFile(String path, File... files) {
    if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("Zipping into:" + path);
    ZipOutputStream zip = null;//from  w  w  w . ja  v  a  2 s. c  om
    FileOutputStream dest = null;
    try {
        File f = new File(path);
        dest = new FileOutputStream(f);
        zip = new ZipOutputStream(new BufferedOutputStream(dest));
        for (File file : files) {
            zip.putNextEntry(new ZipEntry(file.getName()));
            zip.write(FileUtils.readFileToByteArray(file));
            zip.closeEntry();
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Unable to create zip file");
    } finally {
        try {
            if (zip != null)
                zip.close();
            if (dest != null)
                dest.close();

        } catch (Exception ioe) {
            //Nothing to do
        }
    }
}

From source file:com.anritsu.mcrepositorymanager.utils.Packing.java

public Packing(ArrayList<McPackage> packageListToBePacked) {
    this.packageListToBePacked = packageListToBePacked;
    archiveNameFile = new File(REPOSITORY_LOCATION + ARCHIVE_NAME);
    try {/* w  w w.  j a v  a 2s  . co m*/
        out = new ZipOutputStream(new FileOutputStream(archiveNameFile));
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Packing.class.getName()).log(Level.SEVERE, null, ex);
    }

    for (McPackage p : packageListToBePacked) {
        p.setPackageSize(getPackageSize(p));
    }

    // Update status.packageDownloadedSize
    Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override
        public void run() {

            try {
                String fileName = status.getProcessingPackage().getFileName();
                File f = new File(FOLDER_PATH + fileName);
                status.getProcessingPackage().setPackageDownloadedSize(f.length());
            } catch (Exception exp) {
                status.getProcessingPackage().setPackageDownloadedSize(0);
            }
        }
    }, 0, 1000);
}