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.navjagpal.fileshare.StreamingZipEntity.java

public void writeTo(OutputStream out) throws IOException {
    Cursor c = mContentResolver.query(FileSharingProvider.Files.CONTENT_URI,
            new String[] { FileSharingProvider.Files.Columns.DISPLAY_NAME,
                    FileSharingProvider.Files.Columns._DATA },
            FileSharingProvider.Files.Columns.FOLDER_ID + "=?", new String[] { mFolderId }, null);
    ZipOutputStream zipOut = new ZipOutputStream(out);
    byte[] buf = new byte[BUFFER_SIZE];
    while (c.moveToNext()) {
        String filename = c.getString(c.getColumnIndex(FileSharingProvider.Files.Columns.DISPLAY_NAME));
        String data = c.getString(c.getColumnIndex(FileSharingProvider.Files.Columns._DATA));
        zipOut.putNextEntry(new ZipEntry(filename));
        InputStream input = mContentResolver.openInputStream(Uri.parse(data));
        int len;//  w w w .  j a v a  2s. c  o  m
        while ((len = input.read(buf)) > 0) {
            zipOut.write(buf, 0, len);
        }
        zipOut.closeEntry();
        input.close();
    }
    zipOut.finish();
    mFinished = true;
}

From source file:de.uzk.hki.da.pkg.ZipArchiveBuilder.java

public void archiveFolder(File srcFolder, File destFile, boolean includeFolder) throws Exception {

    FileOutputStream fileWriter = new FileOutputStream(destFile);
    ZipOutputStream zip = new ZipOutputStream(fileWriter);

    addFolderToArchive("", srcFolder, zip, includeFolder);

    zip.close();/*  w  ww  .ja v a 2  s. c  o  m*/
    fileWriter.close();
}

From source file:net.gbmb.collector.example.SimpleLogPush.java

private String storeArchive(Collection collection) throws IOException {
    String cid = collection.getId();
    java.util.Collection<CollectionRecord> records = collectionRecords.get(cid);

    // index/*from ww  w . j  a v  a2  s . c o  m*/
    ByteArrayOutputStream indexStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
    PrintStream output = new PrintStream(indexStream);
    // zip
    ByteArrayOutputStream archiveStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
    ZipOutputStream zos = new ZipOutputStream(archiveStream);
    output.println("Serialize collection: " + collection.getId());
    output.println("  creation date: " + collection.getCreationDate());
    output.println("  end date:      " + collection.getEndDate());
    for (CollectionRecord cr : records) {
        output.print(cr.getRecordDate());
        output.print(" ");
        output.println(cr.getContent());
        if (cr.getAttachment() != null) {
            String attName = cr.getAttachment();
            output.println("  > " + attName);
            ZipEntry entry = new ZipEntry(cr.getAttachment());
            zos.putNextEntry(entry);
            InputStream content = temporaryStorage.get(cid, attName);
            IOUtils.copy(content, zos);
        }
    }
    // add the index file
    output.close();
    ZipEntry index = new ZipEntry("index");
    zos.putNextEntry(index);
    IOUtils.write(indexStream.toByteArray(), zos);
    // close zip
    zos.close();
    ByteArrayInputStream content = new ByteArrayInputStream(archiveStream.toByteArray());

    // send to final storage
    return finalStorage.store(cid, content);
}

From source file:org.messic.server.api.APIPlayLists.java

@Transactional
public void getPlaylistZip(User user, Long playlistSid, OutputStream os)
        throws IOException, SidNotFoundMessicException {
    MDOPlaylist mdoplaylist = daoPlaylist.get(user.getLogin(), playlistSid);
    if (mdoplaylist == null) {
        throw new SidNotFoundMessicException();
    }//  w w w .ja  va2s . co m
    List<MDOSong> desiredSongs = mdoplaylist.getSongs();

    ZipOutputStream zos = new ZipOutputStream(os);
    // level - the compression level (0-9)
    zos.setLevel(9);

    HashMap<String, String> songs = new HashMap<String, String>();

    M3U m3u = new M3U();
    m3u.setExtensionM3U(true);
    List<Resource> resources = m3u.getResources();

    for (MDOSong song : desiredSongs) {
        if (song != null) {

            // add file
            // extract the relative name for entry purpose
            String entryName = song.getLocation();
            if (songs.get(entryName) == null) {
                Resource r = new Resource();
                r.setLocation(song.getLocation());
                r.setName(song.getName());
                resources.add(r);

                songs.put(entryName, "ok");
                // song not repeated
                ZipEntry ze = new ZipEntry(entryName);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(song.calculateAbsolutePath(daoSettings.getSettings()));
                int len;
                byte buffer[] = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
            }
        }
    }

    // the last is the playlist m3u
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        m3u.writeTo(baos, "UTF8");
        // song not repeated
        ZipEntry ze = new ZipEntry(mdoplaylist.getName() + ".m3u");
        zos.putNextEntry(ze);
        byte[] bytes = baos.toByteArray();
        zos.write(bytes, 0, bytes.length);
        zos.closeEntry();
    } catch (Exception e) {
        e.printStackTrace();
    }

    zos.close();
}

From source file:com.aionlightning.slf4j.conversion.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * //from   w w w  . java  2  s .  co m
 * @param file
 *            file to truncate
 */
protected void truncate(File file) {
    File backupRoot = new File(backupDir);
    if (!backupRoot.exists() && !backupRoot.mkdirs()) {
        log.warn("Can't create backup dir for backup storage");
        return;
    }

    String date = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        date = reader.readLine().split("\f")[1];
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        zos = new ZipOutputStream(new FileOutputStream(zipFile));
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setMethod(ZipEntry.DEFLATED);
        entry.setCrc(FileUtils.checksumCRC32(file));
        zos.putNextEntry(entry);
        fis = FileUtils.openInputStream(file);

        byte[] buffer = new byte[1024];
        int readed;
        while ((readed = fis.read(buffer)) != -1) {
            zos.write(buffer, 0, readed);
        }

    } catch (Exception e) {
        log.warn("Can't create zip file", e);
    } finally {
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
                log.warn("Can't close zip file", e);
            }
        }

        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.warn("Can't close zipped file", e);
            }
        }
    }

    if (!file.delete()) {
        log.warn("Can't delete old log file " + file.getAbsolutePath());
    }
}

From source file:com.facebook.buck.util.zip.ZipScrubberTest.java

@Test
public void modificationTimesExceedShort() throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] data = "data1".getBytes(Charsets.UTF_8);
    try (ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream)) {
        for (long i = 0; i < Short.MAX_VALUE + 1; i++) {
            ZipEntry entry = new ZipEntry("file" + i);
            entry.setSize(data.length);// w  ww  .j ava  2 s  .  co  m
            out.putNextEntry(entry);
            out.write(data);
            out.closeEntry();
        }
    }

    byte[] bytes = byteArrayOutputStream.toByteArray();
    ZipScrubber.scrubZipBuffer(bytes.length, ByteBuffer.wrap(bytes));

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(bytes))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

From source file:net.sourceforge.jweb.maven.mojo.InWarMinifyMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled)
        return;/* w w w . j a  v a  2s  .c  om*/
    processConfiguration();
    String name = this.getBuilddir().getAbsolutePath() + File.separator + this.getFinalName() + "."
            + this.getPacking();
    this.getLog().info(name);
    MinifyFileFilter fileFilter = new MinifyFileFilter();
    int counter = 0;
    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            //no compress, just transfer to war
            if (!fileFilter.accept(entry)) {
                getLog().debug("nocompress entry: " + entry.getName());
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }

            File sourceTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".tmp");
            File destTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".min.tmp");
            FileUtils.writeStringToFile(sourceTmp, "");
            FileUtils.writeStringToFile(destTmp, "");

            //assemble arguments
            String[] provied = getYuiArguments();
            int length = (provied == null ? 0 : provied.length);
            length += 5;
            int i = 0;

            String[] ret = new String[length];

            ret[i++] = "--type";
            ret[i++] = (entry.getName().toLowerCase().endsWith(".css") ? "css" : "js");

            if (provied != null) {
                for (String s : provied) {
                    ret[i++] = s;
                }
            }

            ret[i++] = sourceTmp.getAbsolutePath();
            ret[i++] = "-o";
            ret[i++] = destTmp.getAbsolutePath();

            try {
                InputStream in = zipFile.getInputStream(entry);
                FileUtils.copyInputStreamToFile(in, sourceTmp);
                in.close();

                YUICompressorNoExit.main(ret);
            } catch (Exception e) {
                this.getLog().warn("compress error, this file will not be compressed:" + buildStack(e));
                FileUtils.copyFile(sourceTmp, destTmp);
            }

            out.putNextEntry(new ZipEntry(entry.getName()));
            InputStream compressedIn = new FileInputStream(destTmp);
            byte[] buf = new byte[512];
            int len = -1;
            while ((len = compressedIn.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            compressedIn.close();

            String sourceSize = decimalFormat.format(sourceTmp.length() * 1.0d / 1024) + " KB";
            String destSize = decimalFormat.format(destTmp.length() * 1.0d / 1024) + " KB";
            getLog().info("compressed entry:" + entry.getName() + " [" + sourceSize + " ->" + destSize + "/"
                    + numberFormat.format(1 - destTmp.length() * 1.0d / sourceTmp.length()) + "]");

            counter++;
        }
        zipFile.close();
        out.close();

        FileUtils.cleanDirectory(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
        FileUtils.forceDelete(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.jaspersoft.studio.community.utils.CommunityAPIUtils.java

/**
 * Creates a ZIP file using the specified zip entries.
 * /*from  w  ww.ja va 2  s  .co m*/
 * @param zipEntries the list of entries that will end up in the final zip file
 * @return the zip file reference
 * @throws CommunityAPIException
 */
public static File createZipFile(List<ZipEntry> zipEntries) throws CommunityAPIException {
    String tmpDirectory = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
    String zipFileLocation = tmpDirectory;
    if (!(tmpDirectory.endsWith("/") || tmpDirectory.endsWith("\\"))) { //$NON-NLS-1$ //$NON-NLS-2$
        zipFileLocation += System.getProperty("file.separator"); //$NON-NLS-1$
    }
    zipFileLocation += "issueDetails.zip"; //$NON-NLS-1$

    try {
        // create byte buffer
        byte[] buffer = new byte[1024];
        // create object of FileOutputStream
        FileOutputStream fout = new FileOutputStream(zipFileLocation);
        // create object of ZipOutputStream from FileOutputStream
        ZipOutputStream zout = new ZipOutputStream(fout);

        for (ZipEntry ze : zipEntries) {
            //create object of FileInputStream for source file
            FileInputStream fin = new FileInputStream(ze.getLocation());
            zout.putNextEntry(new java.util.zip.ZipEntry(ze.getLocation()));
            // After creating entry in the zip file, actually write the file.
            int length;
            while ((length = fin.read(buffer)) > 0) {
                zout.write(buffer, 0, length);
            }
            //close the zip entry and related InputStream
            zout.closeEntry();
            fin.close();
        }
        //close the ZipOutputStream
        zout.close();
    } catch (IOException e) {
        throw new CommunityAPIException(Messages.CommunityAPIUtils_ZipCreationError, e);
    }
    return new File(zipFileLocation);
}

From source file:gov.nih.nci.cabig.caaers.web.ae.AdditionalInformationDocumentZipDownloadController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws ServletRequestBindingException {

    Integer additionalInformationId = ServletRequestUtils.getRequiredIntParameter(request,
            "additionalInformationId");

    List<AdditionalInformationDocument> additionalInformationDocuments = additionalInformationDocumentService
            .findByAdditionalInformationId(additionalInformationId);

    File tempFile = null;/*w w  w  .j  a  v  a2s.  c  o  m*/
    ZipOutputStream zos = null;
    FileOutputStream fos = null;

    List<String> zipEntriesName = new ArrayList<String>();
    try {
        tempFile = File.createTempFile(
                "additionalInformationFile" + System.currentTimeMillis() + RandomUtils.nextInt(1000), ".zip");

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

        for (AdditionalInformationDocument additionalInformationDocument : additionalInformationDocuments) {
            String name = getUniqueZipEntryName(additionalInformationDocument, zipEntriesName);
            zipEntriesName.add(name);
            ZipEntry zipEntry = new ZipEntry(name);
            zos.putNextEntry(zipEntry);
            IOUtils.copy(new FileInputStream(additionalInformationDocument.getFile()), zos);
            zos.closeEntry();
        }

        zos.flush();

    } catch (Exception e) {

        log.error("Unable to create temp file", e);
        return null;
    } finally {
        if (zos != null)
            IOUtils.closeQuietly(zos);
        if (fos != null)
            IOUtils.closeQuietly(fos);
    }

    if (tempFile != null) {

        FileInputStream fis = null;
        OutputStream out = null;
        try {
            fis = new FileInputStream(tempFile);
            out = response.getOutputStream();

            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + additionalInformationId + ".zip");
            response.setHeader("Content-length", String.valueOf(tempFile.length()));
            response.setHeader("Pragma", "private");
            response.setHeader("Cache-control", "private, must-revalidate");

            IOUtils.copy(fis, out);
            out.flush();
        } catch (Exception e) {
            log.error("Error while reading zip file ", e);
        } finally {
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(out);
        }

        FileUtils.deleteQuietly(tempFile);
    }
    return null;
}

From source file:net.grinder.util.LogCompressUtil.java

/**
 * Compress the given file.//www.j a  va 2s.co m
 * 
 * @param logFile
 *            file to be compressed
 * @return compressed file byte array
 */
public static byte[] compressFile(File logFile) {
    FileInputStream fio = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    try {
        fio = new FileInputStream(logFile);
        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        ZipEntry zipEntry = new ZipEntry("log.txt");
        zipEntry.setTime(new Date().getTime());
        zos.putNextEntry(zipEntry);
        byte[] buffer = new byte[COMPRESS_BUFFER_SIZE];
        int count = 0;
        while ((count = fio.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
            zos.write(buffer, 0, count);
        }
        zos.closeEntry();
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.error("Error occurs while compress {}", logFile.getAbsolutePath());
        LOGGER.error("Details", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(fio);
        IOUtils.closeQuietly(out);
    }
}