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.aionlightning.slf4j.conversion.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * /*  w  w w . j a  v a 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:fr.cirad.mgdb.exporting.markeroriented.BEDExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs,
        ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms,
        int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    ZipOutputStream zos = new ZipOutputStream(outputStream);

    if (readyToExportFiles != null)
        for (String readyToExportFile : readyToExportFiles.keySet()) {
            zos.putNextEntry(new ZipEntry(readyToExportFile));
            InputStream inputStream = readyToExportFiles.get(readyToExportFile);
            byte[] dataBlock = new byte[1024];
            int count = inputStream.read(dataBlock, 0, 1024);
            while (count != -1) {
                zos.write(dataBlock, 0, count);
                count = inputStream.read(dataBlock, 0, 1024);
            }/*from   w  w w  .j  a v a2s. co m*/
        }

    int markerCount = markerCursor.count();

    List<String> selectedIndividualList = new ArrayList<String>();
    for (Individual ind : getIndividualsFromSamples(sModule, sampleIDs))
        selectedIndividualList.add(ind.getId());

    String exportName = sModule + "_" + markerCount + "variants_" + selectedIndividualList.size()
            + "individuals";
    zos.putNextEntry(new ZipEntry(exportName + ".bed"));

    short nProgress = 0, nPreviousProgress = 0;
    int nChunkSize = Math.min(2000, markerCount), nLoadedMarkerCount = 0;
    while (markerCursor.hasNext()) {
        int nLoadedMarkerCountInLoop = 0;
        Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>();
        boolean fStartingNewChunk = true;
        markerCursor.batchSize(nChunkSize);
        while (markerCursor.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) {
            DBObject exportVariant = markerCursor.next();
            DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
            markerChromosomalPositions.put((Comparable) exportVariant.get("_id"),
                    refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":"
                            + refPos.get(ReferencePosition.FIELDNAME_START_SITE));
            nLoadedMarkerCountInLoop++;
            fStartingNewChunk = false;
        }

        for (Comparable variantId : markerChromosomalPositions.keySet()) // read data and write results into temporary files (one per sample)
        {
            String[] chromAndPos = markerChromosomalPositions.get(variantId).split(":");
            zos.write((chromAndPos[0] + "\t" + (Long.parseLong(chromAndPos[1]) - 1) + "\t"
                    + (Long.parseLong(chromAndPos[1]) - 1) + "\t" + variantId + "\t" + "0" + "\t" + "+")
                            .getBytes());
            zos.write((LINE_SEPARATOR).getBytes());
        }

        if (progress.hasAborted())
            return;

        nLoadedMarkerCount += nLoadedMarkerCountInLoop;
        nProgress = (short) (nLoadedMarkerCount * 100 / markerCount);
        if (nProgress > nPreviousProgress) {
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }
    }

    zos.close();
    progress.setCurrentStepProgress((short) 100);
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

public static void addFileAndDirectoryToZip(File output, File srcDir, Map<String, ZipEntry> zipEntryMethodMap)
        throws Exception {
    if (output.isDirectory()) {
        throw new IOException("This is a directory!");
    }/*from  w  w w .j  a  v a  2  s  . c om*/
    if (!output.getParentFile().exists()) {
        output.getParentFile().mkdirs();
    }

    if (!output.exists()) {
        output.createNewFile();
    }
    List fileList = getSubFiles(srcDir);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output));
    ZipEntry ze = null;
    byte[] buf = new byte[1024];
    int readLen = 0;
    for (int i = 0; i < fileList.size(); i++) {
        File f = (File) fileList.get(i);
        ze = new ZipEntry(getAbsFileName(srcDir.getPath(), f));
        ze.setSize(f.length());
        ze.setTime(f.lastModified());
        if (zipEntryMethodMap != null) {
            ZipEntry originEntry = zipEntryMethodMap.get(f.getAbsolutePath());
            if (originEntry != null) {
                ze.setCompressedSize(originEntry.getCompressedSize());
                ze.setCrc(originEntry.getCrc());
                ze.setMethod(originEntry.getMethod());
            }
        }
        zos.putNextEntry(ze);
        InputStream is = new BufferedInputStream(new FileInputStream(f));
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            zos.write(buf, 0, readLen);
        }
        is.close();
    }
    zos.close();
}

From source file:org.carlspring.strongbox.artifact.generator.NugetPackageGenerator.java

private void addNugetNuspecFile(Nuspec nuspec, ZipOutputStream zos) throws IOException, JAXBException {
    ZipEntry ze = new ZipEntry(nuspec.getId() + ".nuspec");
    zos.putNextEntry(ze);//from  ww  w . ja v a  2 s. com

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    nuspec.saveTo(baos);

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

    byte[] buffer = new byte[4096];
    int len;
    while ((len = bais.read(buffer)) > 0) {
        zos.write(buffer, 0, len);
    }

    bais.close();
    zos.closeEntry();
}

From source file:org.apache.sling.oakui.OakUIWebConsole.java

private void transferBytes(OakIndexInput input, ZipOutputStream zipOutputStream) throws IOException {
    byte[] buffer = new byte[4096];
    long l = input.length();
    while (l > 0) {
        int rl = (int) Math.min(buffer.length, l);
        input.readBytes(buffer, 0, rl);/* ww w  .  j  ava  2s .  c  o  m*/
        zipOutputStream.write(buffer, 0, rl);
        l = l - rl;
    }
}

From source file:com.stimulus.archiva.presentation.ExportBean.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SearchBean searchBean = (SearchBean) form;

    String outputDir = Config.getFileSystem().getViewPath() + File.separatorChar;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String zipFileName = "export-" + sdf.format(new Date()) + ".zip";
    File zipFile = new File(outputDir + zipFileName);

    String agent = request.getHeader("USER-AGENT");
    if (null != agent && -1 != agent.indexOf("MSIE")) {
        String codedfilename = URLEncoder.encode(zipFileName, "UTF8");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        String codedfilename = MimeUtility.encodeText(zipFileName, "UTF8", "B");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else {/*from   w  ww .  j a  v a 2 s  .co  m*/
        response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
    }

    logger.debug("size of searchResult = " + searchBean.getSearchResults().size());
    //MessageBean.viewMessage
    List<File> files = new ArrayList<File>();
    for (SearchResultBean searchResult : searchBean.getSearchResults()) {
        if (searchResult.getSelected()) {
            Email email = MessageService.getMessageByID(searchResult.getVolumeID(), searchResult.getUniqueID(),
                    false);

            HttpServletRequest hsr = ActionContext.getActionContext().getRequest();
            String baseURL = hsr.getRequestURL().substring(0,
                    hsr.getRequestURL().lastIndexOf(hsr.getServletPath()));
            MessageExtraction messageExtraction = MessageService.extractMessage(email, baseURL, true); // can take a while to extract message

            //              MessageBean mbean = new MessageBean();
            //              mbean.setMessageID(searchResult.getUniqueID());
            //              mbean.setVolumeID(searchResult.getVolumeID());
            //              writer.println(searchResult.toString());
            //              writer.println(messageExtraction.getFileName());

            File fileToAdd = new File(outputDir, messageExtraction.getFileName());
            if (!files.contains(fileToAdd)) {
                files.add(fileToAdd);
            }
        }
    }

    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
    try {
        byte[] buf = new byte[1024];
        for (File f : files) {
            ZipEntry ze = new ZipEntry(f.getName());
            logger.debug("Adding file " + f.getName());
            zos.putNextEntry(ze);
            InputStream is = new BufferedInputStream(new FileInputStream(f));
            for (;;) {
                int len = is.read(buf);
                if (len < 0)
                    break;
                zos.write(buf, 0, len);
            }
            is.close();
            Config.getFileSystem().getTempFiles().markForDeletion(f);
        }
    } finally {
        zos.close();
    }
    logger.debug("download zipped emails {fileName='" + zipFileName + "'}");

    String contentType = "application/zip";
    Config.getFileSystem().getTempFiles().markForDeletion(zipFile);
    return new FileStreamInfo(contentType, zipFile);
}

From source file:org.apache.chemistry.opencmis.tools.specexamples.Main.java

private static void addDirectory(ZipOutputStream zout, String prefix, File sourceDir) throws IOException {

    File[] files = sourceDir.listFiles();
    LOG.debug("Create Zip, adding directory " + sourceDir.getName());

    if (null != files) {
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                addDirectory(zout, prefix + File.separator + files[i].getName(), files[i]);
            } else {
                LOG.debug("Create Zip, adding file " + files[i].getName());
                byte[] buffer = new byte[65536];
                FileInputStream fin = new FileInputStream(files[i]);
                String zipEntryName = prefix + File.separator + files[i].getName();
                LOG.debug("   adding entry " + zipEntryName);
                zout.putNextEntry(new ZipEntry(zipEntryName));

                int length;
                while ((length = fin.read(buffer)) > 0) {
                    zout.write(buffer, 0, length);
                }// w  w  w .ja  v  a2  s . co  m

                zout.closeEntry();
                fin.close();
            }
        }
    }
}

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.//  ww  w  .j av 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:org.ado.minesync.commons.ZipArchiver.java

private void zipFile(ZipOutputStream zout, byte[] data, File file, String directoryName) throws IOException {
    BufferedInputStream origin = null;
    FileInputStream fi = null;/*ww w . j  a v  a 2 s . c o m*/
    try {
        if (file.exists()) {
            fi = new FileInputStream(file);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(getFilePath(file, directoryName));
            zout.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                zout.write(data, 0, count);
            }
        } else {
            ALog.w(TAG, "file \"%s\" does not exist.", file.getName());
        }
    } finally {
        IOUtils.closeQuietly(fi);
        IOUtils.closeQuietly(origin);
    }
}

From source file:nl.imvertor.common.file.ZipFile.java

/**
 * Zip it//from w  ww .j  av a 2 s .  co  m
 * @throws IOException 
 */
// adapted from http://www.mkyong.com/java/how-to-compress-files-in-zip-format/
private void zipIt() throws IOException {
    byte[] buffer = new byte[1024];
    FileOutputStream fos = new FileOutputStream(this);
    ZipOutputStream zos = new ZipOutputStream(fos);
    for (String file : this.fileList) {
        ZipEntry ze = new ZipEntry(file);
        zos.putNextEntry(ze);
        FileInputStream in = new FileInputStream(sourceFolder + File.separator + file);
        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }
        in.close();
    }
    zos.closeEntry();
    zos.close();
}