Example usage for java.util.zip ZipOutputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java

private void updateWithMetaInf(ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly)
        throws IOException {
    ZipFile zin = new ZipFile(jarFile);

    for (Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements();) {
        ZipEntry ze = en.nextElement();

        if (ze.isDirectory()) {
            continue;
        }//from   w  w  w  . j  a v a2s  .  c o m

        String zn = ze.getName();

        if (metaInfOnly) {
            if (!zn.startsWith("META-INF/")) {
                continue;
            }

            if (this.extractDuplicates && !entries.add(zn)) {
                continue;
            }

            if (!this.apkMetaInf.isIncluded(zn)) {
                continue;
            }
        }
        final ZipEntry ne;
        if (ze.getMethod() == ZipEntry.STORED) {
            ne = new ZipEntry(ze);
        } else {
            ne = new ZipEntry(zn);
        }

        zos.putNextEntry(ne);

        InputStream is = zin.getInputStream(ze);

        copyStreamWithoutClosing(is, zos);

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

    zin.close();
}

From source file:brut.androlib.Androlib.java

private void copyUnknownFiles(File appDir, ZipOutputStream outputFile, Map<String, String> files)
        throws IOException {
    File unknownFileDir = new File(appDir, UNK_DIRNAME);

    // loop through unknown files
    for (Map.Entry<String, String> unknownFileInfo : files.entrySet()) {
        File inputFile = new File(unknownFileDir, unknownFileInfo.getKey());
        if (inputFile.isDirectory()) {
            continue;
        }/*from  w ww.  j  ava2  s .  com*/

        ZipEntry newEntry = new ZipEntry(unknownFileInfo.getKey());
        int method = Integer.valueOf(unknownFileInfo.getValue());
        LOGGER.fine(String.format("Copying unknown file %s with method %d", unknownFileInfo.getKey(), method));
        if (method == ZipEntry.STORED) {
            newEntry.setMethod(ZipEntry.STORED);
            newEntry.setSize(inputFile.length());
            newEntry.setCompressedSize(-1);
            BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(inputFile));
            CRC32 crc = BrutIO.calculateCrc(unknownFile);
            newEntry.setCrc(crc.getValue());
        } else {
            newEntry.setMethod(ZipEntry.DEFLATED);
        }
        outputFile.putNextEntry(newEntry);

        BrutIO.copy(inputFile, outputFile);
        outputFile.closeEntry();
    }
}

From source file:middleware.NewServerSocket.java

private boolean zipAllFiles() {

    File zipFile = new File(zipFileName);
    int index = 0;
    while (zipFile.exists()) {
        if (!zipFile.delete()) {
            ++index;/*from   w  w w.j a v  a 2  s  . c om*/
            zipFileName = "LogFiles_" + index + ".zip";
            zipFile = new File(zipFileName);
        }
    }

    try {

        FileOutputStream fos = new FileOutputStream(zipFileName);

        ZipOutputStream zos = new ZipOutputStream(fos);

        File[] files = dir.listFiles();

        for (int i = 0; i < files.length; i++) {

            // only sends the dstat log file.
            if (files[i].getName().contains("log_exp_1")) {
                FileInputStream fis = new FileInputStream(files[i]);

                // begin writing a new ZIP entry, positions the stream to the start of
                // the entry data
                zos.putNextEntry(new ZipEntry(files[i].getName()));

                int length;

                while ((length = fis.read(fileBuffer)) > 0) {
                    zos.write(fileBuffer, 0, length);
                }

                zos.closeEntry();

                // close the InputStream
                fis.close();
            }
        }

        // close the ZipOutputStream
        zos.close();

    } catch (IOException ioe) {
        return false;
    }

    return true;

}

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  w  w. j a v a2  s.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.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 w  w w. j ava2s.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:br.org.indt.ndg.client.Service.java

/**
 *
 * @param surveyIds/*from  w  w w .ja  v a  2 s.  c  om*/
 * @return
 * @throws NDGServerException
 */
public String downloadSurvey(String username, ArrayList<String> surveyIds) throws NDGServerException {

    final String SURVEY = "survey";
    String strFileContent = null;
    byte[] fileContent = null;
    ArrayList<String> arrayStrFileContent;

    try {
        arrayStrFileContent = new ArrayList<String>();

        for (int i = 0; i < surveyIds.size(); i++) {
            arrayStrFileContent.add(i, msmBD.loadSurveyFromServerToEditor(username, surveyIds.get(i)));
        }
    } catch (MSMApplicationException e) {
        e.printStackTrace();
        throw new NDGServerException(e.getErrorCode());
    } catch (Exception e) {
        e.printStackTrace();
        throw new NDGServerException(UNEXPECTED_SERVER_EXCEPTION);
    }

    File f = new File(SURVEY + ZIP);

    ZipOutputStream out = null;
    try {
        out = new ZipOutputStream(new FileOutputStream(f));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < surveyIds.size(); i++) {
        StringBuilder sb = new StringBuilder();
        sb.append(arrayStrFileContent.get(i));

        File zipDir = new File(SURVEY + surveyIds.get(i));

        ZipEntry e = new ZipEntry(zipDir + File.separator + "survey.xml");

        try {
            out.putNextEntry(e);
            byte[] data = sb.toString().getBytes();
            out.write(data, 0, data.length);
            out.closeEntry();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    try {
        out.close();
        fileContent = getBytesFromFile(f);
        strFileContent = Base64Encode.base64Encode(fileContent);

    } catch (IOException e1) {
        e1.printStackTrace();
    }

    f.delete();

    return strFileContent;
}

From source file:com.streamsets.datacollector.bundles.SupportBundleManager.java

private void generateNewBundleInternal(List<BundleContentGenerator> generators, BundleType bundleType,
        ZipOutputStream zipStream) {
    try {//  w  w w  . ja v a2  s.  c om
        Properties runGenerators = new Properties();
        Properties failedGenerators = new Properties();

        // Let each individual content generator run to generate it's content
        for (BundleContentGenerator generator : generators) {
            BundleContentGeneratorDefinition definition = definitionMap
                    .get(generator.getClass().getSimpleName());
            BundleWriterImpl writer = new BundleWriterImpl(definition.getKlass().getName(), redactor,
                    zipStream);

            try {
                LOG.debug("Generating content with {} generator", definition.getKlass().getName());
                generator.generateContent(this, writer);
                runGenerators.put(definition.getKlass().getName(), String.valueOf(definition.getVersion()));
            } catch (Throwable t) {
                LOG.error("Generator {} failed", definition.getName(), t);
                failedGenerators.put(definition.getKlass().getName(), String.valueOf(definition.getVersion()));
                writer.ensureEndOfFile();
            }
        }

        // generators.properties
        zipStream.putNextEntry(new ZipEntry("generators.properties"));
        runGenerators.store(zipStream, "");
        zipStream.closeEntry();

        // failed_generators.properties
        zipStream.putNextEntry(new ZipEntry("failed_generators.properties"));
        failedGenerators.store(zipStream, "");
        zipStream.closeEntry();

        if (!bundleType.isAnonymizeMetadata()) {
            // metadata.properties
            zipStream.putNextEntry(new ZipEntry("metadata.properties"));
            getMetadata(bundleType).store(zipStream, "");
            zipStream.closeEntry();
        }

    } catch (Exception e) {
        LOG.error("Failed to generate resource bundle", e);
    } finally {
        // And that's it
        try {
            zipStream.close();
        } catch (IOException e) {
            LOG.error("Failed to finish generating the bundle", e);
        }
    }
}

From source file:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

/**
 * Zips the contents of a given file containing code coverage results in XML format.
 * @param file The file containing the code coverage XML results.
 * @throws IOException If there are any error reading the file.
 *///from  w  ww .j  a v a 2 s.co m
public void setCodeCoveralXMLResults(File file) throws IOException {
    if (!file.exists() || !file.canRead()) {
        return;
    }
    ByteArrayOutputStream actualData = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(actualData);

    ZipEntry entry = new ZipEntry("coverage");
    zipOut.putNextEntry(entry);

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    try {
        int bytesRead = 0;
        byte[] bytes = new byte[2048];
        while (true) {
            int numBytes = in.read(bytes);
            if (numBytes == -1)
                break;
            zipOut.write(bytes, 0, numBytes);
            bytesRead += numBytes;
        }
        zipOut.closeEntry();
        zipOut.close();
        byte[] outbytes = actualData.toByteArray();
        //       System.out.println("outbytes.length: "+outbytes.length+
        //               " and we read: " +bytesRead+ " total bytes");
        setDetails(outbytes);
    } finally {
        in.close();
    }
}

From source file:com.photon.maven.plugins.android.phase09package.ApkMojo.java

private File removeDuplicatesFromJar(File in, List<String> duplicates) {
    File target = new File(project.getBasedir(), "target");
    File tmp = new File(target, "unpacked-embedded-jars");
    tmp.mkdirs();/*from   w w  w  .j a  v  a2s.c o m*/
    File out = new File(tmp, in.getName());

    if (out.exists()) {
        return out;
    }
    try {
        out.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Create a new Jar file
    FileOutputStream fos = null;
    ZipOutputStream jos = null;
    try {
        fos = new FileOutputStream(out);
        jos = new ZipOutputStream(fos);
    } catch (FileNotFoundException e1) {
        getLog().error(
                "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found");
        return null;
    }

    ZipFile inZip = null;
    try {
        inZip = new ZipFile(in);
        Enumeration<? extends ZipEntry> entries = inZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            // If the entry is not a duplicate, copy.
            if (!duplicates.contains(entry.getName())) {
                // copy the entry header to jos
                jos.putNextEntry(entry);
                InputStream currIn = inZip.getInputStream(entry);
                copyStreamWithoutClosing(currIn, jos);
                currIn.close();
                jos.closeEntry();
            }
        }
    } catch (IOException e) {
        getLog().error("Cannot removing duplicates : " + e.getMessage());
        return null;
    }

    try {
        if (inZip != null) {
            inZip.close();
        }
        jos.close();
        fos.close();
        jos = null;
        fos = null;
    } catch (IOException e) {
        // ignore it.
    }
    getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath());
    return out;
}