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:game.com.HandleDownloadFolderServlet.java

private void outputZipStream(ZipOutputStream output, File file) throws FileNotFoundException, IOException {
    for (File currentFile : file.listFiles()) {

        InputStream input = null;
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        try {//  w  w  w . j av  a 2 s  .com
            if (currentFile.isDirectory()) {
                outputZipStream(output, currentFile);
            } else {
                input = new BufferedInputStream(new FileInputStream(currentFile), DEFAULT_BUFFER_SIZE);
                output.putNextEntry(new ZipEntry(currentFile.getName()));
                for (int length = 0; (length = input.read(buffer)) > 0;) {
                    output.write(buffer, 0, length);
                }
                output.closeEntry();
            }
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (Exception logOrIgnore) {
                    logger.error(logOrIgnore.getMessage(), logOrIgnore);
                }
            }
        }
    }
}

From source file:nl.b3p.viewer.features.ShapeDownloader.java

/**
 * This method zips the directory/*w w  w  . j a  va 2s  . c  o m*/
 *
 * @param dir
 * @param zipDirName
 */
private void zipDirectory(File dir, File zip) throws IOException {
    try {
        List<String> filesListInDir = new ArrayList<String>();
        populateFilesList(dir, filesListInDir);
        //now zip files one by one
        //create ZipOutputStream to write to the zip file
        FileOutputStream fos = new FileOutputStream(zip);
        ZipOutputStream zos = new ZipOutputStream(fos);
        for (String filePath : filesListInDir) {
            //for ZipEntry we need to keep only relative file path, so we used substring on absolute path
            ZipEntry ze = new ZipEntry(
                    filePath.substring(dir.getAbsolutePath().length() + 1, filePath.length()));
            zos.putNextEntry(ze);
            //read the file and write to ZipOutputStream
            FileInputStream fis = new FileInputStream(filePath);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            zos.closeEntry();
            fis.close();
        }
        zos.close();
        fos.close();
    } catch (IOException e) {
        log.error("Could not write zipfile. Exiting.", e);
        throw e;
    }
}

From source file:ZipSourceCallable.java

public static void zipSource(FilePath workspace, final String directory, final ZipOutputStream out,
        final String prefixToTrim) throws Exception {
    if (!Paths.get(directory).startsWith(Paths.get(prefixToTrim))) {
        throw new Exception(zipSourceError + "prefixToTrim: " + prefixToTrim + ", directory: " + directory);
    }//from w w  w . j  av  a 2 s  .  c o  m

    FilePath dir = new FilePath(workspace, directory);
    List<FilePath> dirFiles = dir.list();
    if (dirFiles == null) {
        throw new Exception("Empty or invalid source directory: " + directory
                + ". Did you download any source as part of your build?");
    }
    byte[] buffer = new byte[1024];
    int bytesRead;

    for (int i = 0; i < dirFiles.size(); i++) {
        FilePath f = new FilePath(workspace, dirFiles.get(i).getRemote());
        if (f.isDirectory()) {
            zipSource(workspace, f.getRemote() + File.separator, out, prefixToTrim);
        } else {
            InputStream inputStream = f.read();
            try {
                String path = trimPrefix(f.getRemote(), prefixToTrim);

                if (path.startsWith(File.separator)) {
                    path = path.substring(1, path.length());
                }

                // Zip files created on the windows file system will not unzip
                // properly on unix systems. Without this change, no directory structure
                // is built when unzipping.
                path = path.replace(File.separator, "/");

                ZipEntry entry = new ZipEntry(path);
                out.putNextEntry(entry);
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                inputStream.close();
            }
        }
    }
}

From source file:org.pdfgal.pdfgalweb.utils.impl.ZipUtilsImpl.java

/**
 * Adds a new file to the {@link ZipOutputStream}.
 * //from ww w.  j av a2s.  c o  m
 * @param fileName
 * @param zos
 * @param originalFileName
 * @throws FileNotFoundException
 * @throws IOException
 */
private void addToZipFile(final String fileName, final ZipOutputStream zos, final String originalFileName)
        throws IOException {

    // File is opened.
    final File file = new File(fileName);

    // File is renamed.
    final String newName = fileName.substring(fileName.indexOf(originalFileName), fileName.length());
    final File renamedFile = new File(newName);
    file.renameTo(renamedFile);

    // File is included into ZIP.
    final FileInputStream fis = new FileInputStream(renamedFile);
    final ZipEntry zipEntry = new ZipEntry(newName);
    zos.putNextEntry(zipEntry);

    final byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }

    // Closing elements.
    zos.closeEntry();
    fis.close();

    // File is deleted
    this.fileUtils.delete(newName);
}

From source file:com.esofthead.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java

private void addFileToZip(String path, Content res, ZipOutputStream zip) throws Exception {
    byte[] buf = new byte[1024];
    InputStream contentStream;//from  w  w w.  ja v  a2 s  .  co m
    if (!res.isExternalResource()) {
        contentStream = resourceService.getContentStream(res.getPath());
    } else {
        ExternalResourceService service = ResourceUtils.getExternalResourceService(ResourceUtils.getType(res));
        contentStream = service.download(ResourceUtils.getExternalDrive(res), res.getPath());
    }
    if (path.length() == 0)
        path = res.getName();
    else
        path += "/" + res.getName();
    zip.putNextEntry(new ZipEntry(path));
    int byteLength;
    while ((byteLength = contentStream.read(buf)) > 0) {
        zip.write(buf, 0, byteLength);
    }
}

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

private void zipDir(String basePath, File dir, ZipOutputStream zos) throws IOException {
    byte[] buf = new byte[16384];

    if (dir.listFiles() != null) {
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                String path = basePath + file.getName() + "/";

                zos.putNextEntry(new ZipEntry(path));
                zipDir(path, file, zos);
                zos.closeEntry();//from w  ww. ja  v a2 s  .  com
            } else if (!file.getName().equals(BACKUP_PREFS_FILENAME)) {
                FileInputStream fin = new FileInputStream(file);
                int length;

                zos.putNextEntry(new ZipEntry(basePath + file.getName()));

                while ((length = fin.read(buf)) > 0) {
                    zos.write(buf, 0, length);
                }

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

From source file:com.polyvi.xface.extension.zip.XZipExt.java

/**
 * ??zip// www . j av  a 2  s.c  o  m
 *
 * @param srcIs
 * @param zos
 * @throws IOException
 * @throws IllegalArgumentException
 */
private void writeToZip(InputStream srcIs, ZipOutputStream zos) throws IOException, IllegalArgumentException {
    if (null == srcIs || null == zos) {
        XLog.e(CLASS_NAME, "Method writeToZip: param is null!");
        throw new IllegalArgumentException();
    }
    try {
        byte[] readBuffer = new byte[XConstant.BUFFER_LEN];
        int bytesIn = 0;
        bytesIn = srcIs.read(readBuffer);
        while (bytesIn != -1) {
            zos.write(readBuffer, 0, bytesIn);
            bytesIn = srcIs.read(readBuffer);
        }
    } catch (IOException e) {
        XLog.e(CLASS_NAME, "Zip file failed!");
        throw new IOException();
    } finally {
        srcIs.close();
        zos.closeEntry();
    }
}

From source file:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Generates a zip file./* www.  j a v  a  2 s. c  o  m*/
 *
 * @param source      source file or directory to compress.
 * @param destination destination of zipped file.
 * @return the zipped file.
 */
private void generateZip(File source, File destination) throws IOException {
    if (source == null || !source.exists()) {
        throw new IllegalArgumentException("source file should exist");
    }
    if (destination == null) {
        throw new IllegalArgumentException("destination file should be not null");
    }

    FileOutputStream output = new FileOutputStream(destination);
    ZipOutputStream zip_out = new ZipOutputStream(output);
    zip_out.setLevel(cfgManager.getDownloadConfiguration().getCompressionLevel());

    List<QualifiedFile> file_list = getFileList(source);
    byte[] buffer = new byte[BUFFER_SIZE];
    for (QualifiedFile qualified_file : file_list) {
        ZipEntry entry = new ZipEntry(qualified_file.getQualifier());
        InputStream input = new FileInputStream(qualified_file.getFile());

        int read;
        zip_out.putNextEntry(entry);
        while ((read = input.read(buffer)) != -1) {
            zip_out.write(buffer, 0, read);
        }
        input.close();
        zip_out.closeEntry();
    }
    zip_out.close();
    output.close();
}

From source file:com.yifanlu.PSXperiaTool.ZpakCreate.java

public void create(boolean noCompress) throws IOException {
    Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(),
            !noCompress);//from w  w w . j a  v  a2 s. c  om
    IOFileFilter filter = new IOFileFilter() {
        public boolean accept(File file) {
            if (file.getName().startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }

        public boolean accept(File file, String s) {
            if (s.startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }
    };
    Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE);
    ZipOutputStream out = new ZipOutputStream(mOut);
    out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED);
    while (it.hasNext()) {
        File current = it.next();
        FileInputStream in = new FileInputStream(current);
        ZipEntry zEntry = new ZipEntry(
                current.getPath().replace(mDirectory.getPath(), "").substring(1).replace("\\", "/"));
        if (noCompress) {
            zEntry.setSize(in.getChannel().size());
            zEntry.setCompressedSize(in.getChannel().size());
            zEntry.setCrc(getCRC32(current));
        }
        out.putNextEntry(zEntry);
        Logger.verbose("Adding file %s", current.getPath());
        int n;
        while ((n = in.read(mBuffer)) != -1) {
            out.write(mBuffer, 0, n);
        }
        in.close();
        out.closeEntry();
    }
    out.close();
    Logger.debug("Done with ZPAK creation.");
}

From source file:fr.cirad.mgdb.exporting.individualoriented.PLinkExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, Collection<File> individualExportFiles,
        boolean fDeleteSampleExportFilesOnExit, ProgressIndicator progress, DBCursor markerCursor,
        Map<Comparable, Comparable> markerSynonyms, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);

    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  ww  .jav a 2 s  .co  m*/
        }

    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    int markerCount = markerCursor.count();

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

    TreeMap<Integer, Comparable> problematicMarkerIndexToNameMap = new TreeMap<Integer, Comparable>();
    short nProgress = 0, nPreviousProgress = 0;
    int i = 0;
    for (File f : individualExportFiles) {
        BufferedReader in = new BufferedReader(new FileReader(f));
        try {
            String individualId, line = in.readLine(); // read sample id
            if (line != null) {
                individualId = line;
                String population = getIndividualPopulation(sModule, line);
                String individualInfo = (population == null ? "." : population) + " " + individualId;
                zos.write((individualInfo + " 0 0 0 " + getIndividualGenderCode(sModule, individualId))
                        .getBytes());
            } else
                throw new Exception("Unable to read first line of temp export file " + f.getName());

            int nMarkerIndex = 0;
            while ((line = in.readLine()) != null) {
                List<String> genotypes = MgdbDao.split(line, "|");
                HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes
                int highestGenotypeCount = 0;
                String mostFrequentGenotype = null;
                for (String genotype : genotypes) {
                    if (genotype.length() == 0)
                        continue; /* skip missing genotypes */

                    int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                    if (gtCount > highestGenotypeCount) {
                        highestGenotypeCount = gtCount;
                        mostFrequentGenotype = genotype;
                    }
                    genotypeCounts.put(genotype, gtCount);
                }

                if (genotypeCounts.size() > 1) {
                    warningFileWriter.write("- Dissimilar genotypes found for variant " + nMarkerIndex
                            + ", individual " + individualId + ". Exporting most frequent: "
                            + mostFrequentGenotype + "\n");
                    problematicMarkerIndexToNameMap.put(nMarkerIndex, "");
                }

                String[] alleles = mostFrequentGenotype == null ? new String[0]
                        : mostFrequentGenotype.split(" ");
                if (alleles.length > 2) {
                    warningFileWriter.write("- More than 2 alleles found for variant " + nMarkerIndex
                            + ", individual " + individualId + ". Exporting only the first 2 alleles.\n");
                    problematicMarkerIndexToNameMap.put(nMarkerIndex, "");
                }

                String all1 = alleles.length == 0 ? "0" : alleles[0];
                String all2 = alleles.length == 0 ? "0" : alleles[alleles.length == 1 ? 0 : 1];
                if (all1.length() != 1 || all2.length() != 1) {
                    warningFileWriter
                            .write("- SNP expected, but alleles are not coded on a single char for variant "
                                    + nMarkerIndex + ", individual " + individualId
                                    + ". Ignoring this genotype.\n");
                    problematicMarkerIndexToNameMap.put(nMarkerIndex, "");
                } else
                    zos.write((" " + all1 + " " + all2).getBytes());

                nMarkerIndex++;
            }
        } catch (Exception e) {
            LOG.error("Error exporting data", e);
            progress.setError("Error exporting data: " + e.getClass().getSimpleName()
                    + (e.getMessage() != null ? " - " + e.getMessage() : ""));
            return;
        } finally {
            in.close();
        }

        if (progress.hasAborted())
            return;

        nProgress = (short) (++i * 100 / individualExportFiles.size());
        if (nProgress > nPreviousProgress) {
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }
        zos.write('\n');

        if (!f.delete()) {
            f.deleteOnExit();
            LOG.info("Unable to delete tmp export file " + f.getAbsolutePath());
        }
    }
    warningFileWriter.close();

    zos.putNextEntry(new ZipEntry(exportName + ".map"));

    int avgObjSize = (Integer) mongoTemplate
            .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize");
    int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;

    markerCursor.batchSize(nChunkSize);
    int nMarkerIndex = 0;
    while (markerCursor.hasNext()) {
        DBObject exportVariant = markerCursor.next();
        DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
        Comparable markerId = (Comparable) exportVariant.get("_id");
        String chrom = (String) refPos.get(ReferencePosition.FIELDNAME_SEQUENCE);
        Long pos = ((Number) refPos.get(ReferencePosition.FIELDNAME_START_SITE)).longValue();

        if (chrom == null)
            LOG.warn("Chromosomal position not found for marker " + markerId);
        Comparable exportedId = markerSynonyms == null ? markerId : markerSynonyms.get(markerId);
        zos.write(((chrom == null ? "0" : chrom) + " " + exportedId + " " + 0 + " " + (pos == null ? 0 : pos)
                + LINE_SEPARATOR).getBytes());

        if (problematicMarkerIndexToNameMap.containsKey(nMarkerIndex)) { // we are going to need this marker's name for the warning file
            Comparable variantName = markerId;
            if (markerSynonyms != null) {
                Comparable syn = markerSynonyms.get(markerId);
                if (syn != null)
                    variantName = syn;
            }
            problematicMarkerIndexToNameMap.put(nMarkerIndex, variantName);
        }
        nMarkerIndex++;
    }

    if (warningFile.length() > 0) {
        zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
        int nWarningCount = 0;
        BufferedReader in = new BufferedReader(new FileReader(warningFile));
        String sLine;
        while ((sLine = in.readLine()) != null) {
            for (Integer aMarkerIndex : problematicMarkerIndexToNameMap.keySet())
                sLine = sLine.replaceAll("__" + aMarkerIndex + "__",
                        problematicMarkerIndexToNameMap.get(aMarkerIndex).toString());
            zos.write((sLine + "\n").getBytes());
            in.readLine();
            nWarningCount++;
        }
        LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
        in.close();
    }
    warningFile.delete();

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