Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

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   www. ja  v  a2  s  .  com
        }

    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.ibm.cics.ca1y.Emit.java

/**
 * Create a zip file containing a file entry for each of the required properties.
 * //from   w  w w .  j a  v  a 2 s  .  c om
 * @param properties
 *            - comma-separated list of properties to include in the zip
 * @param props
 *            - EmitProperties that contains the properties to include
 * @return byte[] that represents the zip
 */
private static byte[] createZip(String properties, EmitProperties props) throws IOException {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(messages.getString("AboutToCreateZip") + " " + properties);
    }

    List<String> propertyList = Arrays.asList(properties.split("\\s*,\\s*"));
    Iterator<String> i = propertyList.iterator();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ZipOutputStream zipfile = new ZipOutputStream(bos);
    ZipEntry zipentry = null;

    while (i.hasNext()) {
        String key = (String) i.next();

        // Set the file name of zip entry
        if (props.getPropertyAlternateName(key) != null) {
            zipentry = new ZipEntry(props.getPropertyAlternateName(key));

        } else {
            zipentry = new ZipEntry(key);
        }

        // Put the zip entry into the zip
        zipfile.putNextEntry(zipentry);

        // Write the property contents into the zip entry
        if (props.getPropertyAttachment(key) != null) {
            zipfile.write(props.getPropertyAttachment(key));

        } else {
            // Windows requires text files use CR+LF, so replace \n with \r\n
            String property = props.getProperty(key);

            if (property != null) {
                zipfile.write(property.replaceAll("\n", "\r\n").getBytes("UTF-8"));
            }
        }

        // Remove the property MIME to prevent it from becoming an attachment. Do not remove the property itself as
        // it may be used elsewhere
        props.setPropertyMime(key, null);
    }

    zipfile.close();

    return bos.toByteArray();
}

From source file:com.hichinaschool.flashcards.async.DeckTask.java

private TaskData doInBackgroundExportApkg(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundExportApkg");
    Object[] data = params[0].getObjArray();
    String colPath = (String) data[0];
    String apkgPath = (String) data[1];
    boolean includeMedia = (Boolean) data[2];

    byte[] buf = new byte[1024];
    try {/* w ww.  j  a  v a2s.  c  om*/
        try {
            AnkiDb d = AnkiDatabaseManager.getDatabase(colPath);
        } catch (SQLiteDatabaseCorruptException e) {
            // collection is invalid
            return new TaskData(false);
        } finally {
            AnkiDatabaseManager.closeDatabase(colPath);
        }

        // export collection
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(apkgPath));
        FileInputStream colFin = new FileInputStream(colPath);
        ZipEntry ze = new ZipEntry("collection.anki2");
        zos.putNextEntry(ze);
        int len;
        while ((len = colFin.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        colFin.close();

        // export media
        JSONObject media = new JSONObject();
        if (includeMedia) {
            File mediaDir = new File(AnkiDroidApp.getCurrentAnkiDroidMediaDir());
            if (mediaDir.exists() && mediaDir.isDirectory()) {
                File[] mediaFiles = mediaDir.listFiles();
                int c = 0;
                for (File f : mediaFiles) {
                    FileInputStream mediaFin = new FileInputStream(f);
                    ze = new ZipEntry(Integer.toString(c));
                    zos.putNextEntry(ze);
                    while ((len = mediaFin.read(buf)) >= 0) {
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                    media.put(Integer.toString(c), f.getName());
                }
            }
        }
        ze = new ZipEntry("media");
        zos.putNextEntry(ze);
        InputStream mediaIn = new ByteArrayInputStream(Utils.jsonToString(media).getBytes("UTF-8"));
        while ((len = mediaIn.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        zos.close();
    } catch (FileNotFoundException e) {
        return new TaskData(false);
    } catch (IOException e) {
        return new TaskData(false);
    } catch (JSONException e) {
        return new TaskData(false);
    }
    return new TaskData(true);
}

From source file:com.jtschohl.androidfirewall.MainActivity.java

/**
 * Zip error reports//from w  w  w.j ava2s .com
 */

public void zipFiles() {
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File(sdCard.getAbsolutePath() + "/af_error_reports/");
    String filename = "af_error_reports.zip";
    String[] reports = { dir + "/iptables.txt", dir + "/logcat.txt", dir + "/interfaces.txt" };
    File file = new File(dir, filename);

    try {
        BufferedInputStream origin = null;
        FileOutputStream dest = new FileOutputStream(file);
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
        byte data[] = new byte[2048];

        for (int i = 0; i < reports.length; i++) {
            Log.v(TAG, "Compressing folder: " + reports[i]);
            FileInputStream fi = new FileInputStream(reports[i]);
            origin = new BufferedInputStream(fi, 2048);
            ZipEntry entry = new ZipEntry(reports[i].substring(reports[i].lastIndexOf("/") + 1));
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, 2048)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }
        out.close();
        Toast.makeText(MainActivity.this, R.string.generate_zip, Toast.LENGTH_SHORT).show();
        emailErrorReports();
    } catch (Exception e) {
        Log.e(TAG, "Error zipping folder");
        e.printStackTrace();
    }
}

From source file:com.nit.async.DeckTask.java

private TaskData doInBackgroundExportApkg(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundExportApkg");
    Object[] data = params[0].getObjArray();
    String colPath = (String) data[0];
    String apkgPath = (String) data[1];
    boolean includeMedia = true; //(Boolean) data[2];

    byte[] buf = new byte[1024];
    try {//from  www.  ja v  a2s  .  c o  m
        try {
            AnkiDb d = AnkiDatabaseManager.getDatabase(colPath);
        } catch (SQLiteDatabaseCorruptException e) {
            // collection is invalid
            return new TaskData(false);
        } finally {
            AnkiDatabaseManager.closeDatabase(colPath);
        }

        // export collection
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(apkgPath));
        FileInputStream colFin = new FileInputStream(colPath);
        ZipEntry ze = new ZipEntry("collection.anki2");
        zos.putNextEntry(ze);
        int len;
        while ((len = colFin.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        colFin.close();

        // export media
        JSONObject media = new JSONObject();
        if (includeMedia) {
            File mediaDir = new File(AnkiDroidApp.getCurrentAnkiDroidMediaDir());
            if (mediaDir.exists() && mediaDir.isDirectory()) {
                File[] mediaFiles = mediaDir.listFiles();
                int c = 0;
                for (File f : mediaFiles) {
                    FileInputStream mediaFin = new FileInputStream(f);
                    ze = new ZipEntry(Integer.toString(c));
                    zos.putNextEntry(ze);
                    while ((len = mediaFin.read(buf)) >= 0) {
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                    media.put(Integer.toString(c), f.getName());
                    c++;
                }
            }
        }
        ze = new ZipEntry("media");
        zos.putNextEntry(ze);
        InputStream mediaIn = new ByteArrayInputStream(Utils.jsonToString(media).getBytes("UTF-8"));
        while ((len = mediaIn.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        zos.close();
    } catch (FileNotFoundException e) {
        return new TaskData(false);
    } catch (IOException e) {
        return new TaskData(false);
    } catch (JSONException e) {
        return new TaskData(false);
    }
    return new TaskData(true);
}

From source file:it.govpay.web.rs.dars.anagrafica.domini.DominiHandler.java

@Override
public String esporta(Long idToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]";

    try {// w w w . j a v  a  2  s  .  c o m
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);

        DominiBD dominiBD = new DominiBD(bd);

        Dominio dominio = dominiBD.getDominio(idToExport);
        String fileName = "Dominio_" + dominio.getCodDominio() + ".zip";

        IbanAccreditoBD ibanAccreditoDB = new IbanAccreditoBD(bd);
        IbanAccreditoFilter filter = ibanAccreditoDB.newFilter();
        filter.setIdDominio(idToExport);
        List<IbanAccredito> ibans = ibanAccreditoDB.findAll(filter);
        final byte[] contiAccredito = DominioUtils.buildInformativaContoAccredito(dominio, ibans);

        ZipEntry contiAccreditoXml = new ZipEntry("contiAccredito.xml");
        zout.putNextEntry(contiAccreditoXml);
        zout.write(contiAccredito);
        zout.closeEntry();

        final byte[] informativa = DominioUtils.buildInformativaControparte(dominio, true);

        ZipEntry informativaXml = new ZipEntry("informativa.xml");
        zout.putNextEntry(informativaXml);
        zout.write(informativa);
        zout.closeEntry();

        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:com.netpace.aims.controller.application.WapApplicationHelper.java

public static boolean createWapImagesZipFile(File imagesZipFile, String imageFileName, Long wapApplicationID,
        Long allianceID) throws AimsException, HibernateException {

    byte[] buf = new byte[1024];// Create a buffer for reading the files
    boolean zipCreated = false;
    ZipOutputStream zipOut = null;
    InputStream imgInput = null;//w w  w . j ava  2s . c  o  m

    //general exception for zip creation
    AimsException aimsException = new AimsException("Error");
    aimsException.addException(new AimsException("error.wap.app.zip.create"));

    String fileExtension = "";
    String fName = "";
    String[] imagesDirNames = new String[] { "img_174", "img_240", "img_320" };

    //if images not found, then this statement throws aims exception
    AimsTempFile[] wapImageFiles = WapApplicationHelper.getImagesTempFiles(wapApplicationID, allianceID);

    try {
        zipOut = new ZipOutputStream(new FileOutputStream(imagesZipFile));
        // Compress the files
        for (int i = 0; i < wapImageFiles.length; i++) {
            try {
                imgInput = wapImageFiles[i].getTempFile().getBinaryStream();

                //get extension of filename in lower case
                fName = wapImageFiles[i].getTempFileName();
                fileExtension = (fName.substring(fName.lastIndexOf("."))).toLowerCase();

                // Add ZIP entry to output stream. dirName/filename+extension
                zipOut.putNextEntry(new ZipEntry(imagesDirNames[i] + "/" + (imageFileName + fileExtension)));
                // Transfer bytes from the file to the ZIP file
                int len;
                while ((len = imgInput.read(buf)) > 0) {
                    zipOut.write(buf, 0, len);
                }
            } //end try
            catch (SQLException sqle) {
                System.out.println("Problem in getting image file as stream");
                sqle.printStackTrace(); //
                throw aimsException;
            } catch (IOException e) {
                System.out.println("Problem in adding zip entry");
                e.printStackTrace();
                throw aimsException;
            } finally {
                // Complete the entry
                try {
                    zipOut.closeEntry();
                    imgInput.close();
                } catch (IOException ioe) {
                    System.out.println("Error closing zip entry or input stream for image");
                    ioe.printStackTrace();
                }
            } //end finally
        } //end for
        zipCreated = true;
        log.debug("wap images zip file created for ftp transfer: " + imagesZipFile.getName() + " in directory: "
                + imagesZipFile.getAbsolutePath());
    } catch (FileNotFoundException e) {
        System.out.println(imagesZipFile + " not found in temp directory: " + imagesZipFile.getAbsolutePath());
        e.printStackTrace();//zip file not found
        throw aimsException;
    }

    finally {
        try {
            if (zipOut != null) {
                zipOut.close();
            }
        } catch (IOException e) {
            System.out.println("Error closing zip stream");
            e.printStackTrace();
            System.out.println("deleting zip file: " + imagesZipFile.delete());
            throw aimsException;
        }
    }
    return zipCreated;
}

From source file:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

private void convertOutputZip(String userId, String workflowId, String jobId, String fileName, InputStream is,
        OutputStream os) throws IOException {

    InputStream exactFile = null;
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;//from   w ww .  j a  va  2  s.com
    String runtimeID = getRuntimeID(userId, workflowId);
    ZipOutputStream zos = new ZipOutputStream(os);
    while ((entry = zis.getNextEntry()) != null) {

        if (jobId == null || (entry.getName().contains(jobId + "/outputs/" + runtimeID + "/")
                && (fileName == null || (fileName != null && entry.getName().endsWith(fileName))))) {
            int size;
            byte[] buffer = new byte[2048];

            String parentDir = entry.getName().split("/")[entry.getName().split("/").length - 2];
            String fileNameInZip = parentDir + "/"
                    + entry.getName().split("/")[entry.getName().split("/").length - 1];
            ZipEntry newFile = new ZipEntry(fileNameInZip);
            zos.putNextEntry(newFile);

            while ((size = zis.read(buffer, 0, buffer.length)) != -1) {

                zos.write(buffer, 0, size);
            }
            zos.closeEntry();

        }
    }
    zis.close();
    zos.close();

}

From source file:com.googlecode.dex2jar.v3.DexExceptionHandlerImpl.java

public void dumpException(DexFileReader reader, File errorFile) throws IOException {
    for (Map.Entry<Method, Exception> e : exceptions.entrySet()) {
        System.err.println("Error:" + e.getKey().toString() + "->" + e.getValue().getMessage());
    }/* ww w . ja  v  a 2  s .  c  o  m*/

    final ZipOutputStream errorZipOutputStream = new ZipOutputStream(FileUtils.openOutputStream(errorFile));
    errorZipOutputStream.putNextEntry(new ZipEntry("summary.txt"));
    final PrintWriter fw = new PrintWriter(new OutputStreamWriter(errorZipOutputStream, "UTF-8"));
    fw.println(getVersionString());
    fw.println("there are " + exceptions.size() + " error methods");
    fw.print("options: ");
    if ((readerConfig & DexFileReader.SKIP_DEBUG) == 0) {
        fw.print(" -d");
    }
    fw.println();
    fw.flush();
    errorZipOutputStream.closeEntry();
    final Out out = new Out() {

        @Override
        public void pop() {

        }

        @Override
        public void push() {

        }

        @Override
        public void s(String s) {
            fw.println(s);
        }

        @Override
        public void s(String format, Object... arg) {
            fw.println(String.format(format, arg));
        }
    };
    final int[] count = new int[] { 0 };
    reader.accept(new EmptyVisitor() {

        @Override
        public DexClassVisitor visit(int accessFlags, String className, String superClass,
                String[] interfaceNames) {
            return new EmptyVisitor() {

                @Override
                public DexMethodVisitor visitMethod(final int accessFlags, final Method method) {
                    if (exceptions.containsKey(method)) {
                        return new EmptyVisitor() {

                            @Override
                            public DexCodeVisitor visitCode() {
                                try {
                                    errorZipOutputStream.putNextEntry(new ZipEntry("t" + count[0]++ + ".txt"));
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                                Exception exception = exceptions.get(method);
                                exception.printStackTrace(fw);
                                out.s("");
                                out.s("DexMethodVisitor mv=cv.visitMethod(%s, %s);",
                                        Escape.methodAcc(accessFlags), Escape.v(method));
                                out.s("DexCodeVisitor code = mv.visitCode();");
                                return new ASMifierCodeV(out);
                            }

                            @Override
                            public void visitEnd() {
                                out.s("mv.visitEnd();");
                                fw.flush();
                                try {
                                    errorZipOutputStream.closeEntry();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        };
                    }
                    return null;
                }

            };
        }

    }, readerConfig);
    errorZipOutputStream.close();

}

From source file:com.ichi2.libanki.Media.java

/**
 * Unlike python, our temp zip file will be on disk instead of in memory. This avoids storing
 * potentially large files in memory which is not feasible with Android's limited heap space.
 * <p>/*ww  w  .  j  av  a  2  s.  c om*/
 * Notes:
 * <p>
 * - The maximum size of the changes zip is decided by the constant SYNC_ZIP_SIZE. If a media file exceeds this
 * limit, only that file (in full) will be zipped to be sent to the server.
 * <p>
 * - This method will be repeatedly called from MediaSyncer until there are no more files (marked "dirty" in the DB)
 * to send.
 * <p>
 * - Since AnkiDroid avoids scanning the media folder on every sync, it is possible for a file to be marked as a
 * new addition but actually have been deleted (e.g., with a file manager). In this case we skip over the file
 * and mark it as removed in the database. (This behaviour differs from the desktop client).
 * <p>
 */
public Pair<File, List<String>> mediaChangesZip() {
    File f = new File(mCol.getPath().replaceFirst("collection\\.anki2$", "tmpSyncToServer.zip"));
    Cursor cur = null;
    try {
        ZipOutputStream z = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
        z.setMethod(ZipOutputStream.DEFLATED);

        List<String> fnames = new ArrayList<String>();
        // meta is a list of (fname, zipname), where zipname of null is a deleted file
        // NOTE: In python, meta is a list of tuples that then gets serialized into json and added
        // to the zip as a string. In our version, we use JSON objects from the start to avoid the
        // serialization step. Instead of a list of tuples, we use JSONArrays of JSONArrays.
        JSONArray meta = new JSONArray();
        int sz = 0;
        byte buffer[] = new byte[2048];
        cur = mDb.getDatabase()
                .rawQuery("select fname, csum from media where dirty=1 limit " + Consts.SYNC_ZIP_COUNT, null);

        for (int c = 0; cur.moveToNext(); c++) {
            String fname = cur.getString(0);
            String csum = cur.getString(1);
            fnames.add(fname);
            String normname = HtmlUtil.nfcNormalized(fname);

            if (!TextUtils.isEmpty(csum)) {
                try {
                    mCol.log("+media zip " + fname);
                    File file = new File(dir(), fname);
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 2048);
                    z.putNextEntry(new ZipEntry(Integer.toString(c)));
                    int count = 0;
                    while ((count = bis.read(buffer, 0, 2048)) != -1) {
                        z.write(buffer, 0, count);
                    }
                    z.closeEntry();
                    bis.close();
                    meta.put(new JSONArray().put(normname).put(Integer.toString(c)));
                    sz += file.length();
                } catch (FileNotFoundException e) {
                    // A file has been marked as added but no longer exists in the media directory.
                    // Skip over it and mark it as removed in the db.
                    removeFile(fname);
                }
            } else {
                mCol.log("-media zip " + fname);
                meta.put(new JSONArray().put(normname).put(""));
            }
            if (sz >= Consts.SYNC_ZIP_SIZE) {
                break;
            }
        }

        z.putNextEntry(new ZipEntry("_meta"));
        z.write(Utils.jsonToString(meta).getBytes());
        z.closeEntry();
        z.close();
        // Don't leave lingering temp files if the VM terminates.
        f.deleteOnExit();
        return new Pair<File, List<String>>(f, fnames);
    } catch (IOException e) {
        Timber.e("Failed to create media changes zip", e);
        throw new RuntimeException(e);
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
}