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.recomdata.transmart.data.export.util.ZipUtil.java

/**
 * This method will bundle all the files into a zip file. 
 * If there are 2 files with the same name, only the first file is part of the zip.
 * /*from w  ww .  j a  v a 2  s.  com*/
 * @param zipFileName
 * @param files
 * 
 * @return zipFile absolute path
 * 
 */
public static String bundleZipFile(String zipFileName, List<File> files) {
    File zipFile = null;
    Map<String, File> filesMap = new HashMap<String, File>();

    if (StringUtils.isEmpty(zipFileName))
        return null;

    try {
        zipFile = new File(zipFileName);
        if (zipFile.exists() && zipFile.isFile() && zipFile.delete()) {
            zipFile = new File(zipFileName);
        }

        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
        zipOut.setLevel(ZipOutputStream.DEFLATED);
        byte[] buffer = new byte[BUFFER_SIZE];

        for (File file : files) {
            if (filesMap.containsKey(file.getName())) {
                continue;
            } else if (file.exists() && file.canRead()) {
                filesMap.put(file.getName(), file);
                zipOut.putNextEntry(new ZipEntry(file.getName()));
                FileInputStream fis = new FileInputStream(file);
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    zipOut.write(buffer, 0, bytesRead);
                }
                zipOut.flush();
                zipOut.closeEntry();
            }
        }
        zipOut.finish();
        zipOut.close();
    } catch (IOException e) {
        //log.error("Error while creating Zip file");
    }

    return (null != zipFile) ? zipFile.getAbsolutePath() : null;
}

From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java

/**
 * saves a sound package with all meta information and audio files to a ZIP
 * file and creates the security tokens.
 *
 * @param packageFile the zip file, where the soundpackage should be stored
 * @param soundPackage the sound package info
 * @throws com.dreikraft.infactory.sound.SoundPackageException encapsulates
 * all low level (IO) exceptions/*from   w  ww .j ava2s  . c o m*/
 */
public static void exportSoundPackage(final File packageFile, final SoundPackage soundPackage)
        throws SoundPackageException {

    if (packageFile == null) {
        throw new SoundPackageException(new IllegalArgumentException("null package file"));
    }

    if (packageFile.delete()) {
        log.info("successfully deleted file: " + packageFile.getAbsolutePath());
    }

    ZipOutputStream out = null;
    InputStream in = null;
    try {
        out = new ZipOutputStream(new FileOutputStream(packageFile));
        out.setLevel(9);

        // write package info
        writePackageInfoZipEntry(soundPackage, out);

        // create path entries
        ZipEntry soundDir = new ZipEntry(SOUNDS_PATH_PREFIX + SL);
        out.putNextEntry(soundDir);
        out.flush();
        out.closeEntry();

        // write files
        for (Sound sound : soundPackage.getSounds()) {
            File axboFile = new File(sound.getAxboFile().getPath());
            in = new FileInputStream(axboFile);
            writeZipEntry(SOUNDS_PATH_PREFIX + SL + axboFile.getName(), out, in);
            in.close();
        }
    } catch (FileNotFoundException ex) {
        throw new SoundPackageException(ex);
    } catch (IOException ex) {
        throw new SoundPackageException(ex);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ex) {
                log.error("failed to close ZipOutputStream", ex);
            }
        }
        try {
            if (in != null)
                in.close();
        } catch (IOException ex) {
            log.error("failed to close FileInputStream", ex);
        }
    }
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Add a file to a ZIP archive.
 * @param zos The ZipOutputStream representing the ZIP archive.
 * @param file The File which is to be added to the ZIP archive.
 * @return True if adding succeeded./*from  w w w .  j  av a  2 s  . c  o  m*/
 * @throws IOException Any exception when reading/writing data.
 */
private static boolean zipFile(final ZipOutputStream zos, final File file) throws IOException {
    if (!file.canRead()) {
        logger.error("zipFile can not read " + file.getCanonicalPath());
        return false;
    }
    zos.putNextEntry(new ZipEntry(file.getName()));
    FileInputStream fis = new FileInputStream(file);

    byte[] buffer = new byte[BUFFER_SIZE];
    int byteCount = 0;
    while ((byteCount = fis.read(buffer)) != -1) {
        zos.write(buffer, 0, byteCount);
    }
    fis.close();
    zos.closeEntry();
    return true;
}

From source file:org.envirocar.app.util.Util.java

/**
 * Zips a list of files into the target archive.
 * /*from   w ww  .  ja v a 2 s. co  m*/
 * @param files
 *            the list of files of the target archive
 * @param target
 *            the target filename
 * @throws IOException 
 */
public static void zipNative(List<File> files, String target) throws IOException {
    ZipOutputStream zos = null;
    try {
        File targetFile = new File(target);
        FileOutputStream dest = new FileOutputStream(targetFile);

        zos = new ZipOutputStream(new BufferedOutputStream(dest));

        for (File f : files) {
            byte[] bytes = readFileContents(f).toByteArray();
            ZipEntry entry = new ZipEntry(f.getName());
            zos.putNextEntry(entry);
            zos.write(bytes);
            zos.closeEntry();
        }

    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (zos != null)
                zos.close();
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
        }
    }

}

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

/**
 * Compress multiple Files./*from ww  w  .j  a v  a  2s . c om*/
 * 
 * @param logFiles
 *            files to be compressed
 * @return compressed file byte array
 */
public static byte[] compressFile(File[] logFiles) {
    FileInputStream fio = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    try {

        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        for (File each : logFiles) {
            try {
                fio = new FileInputStream(each);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                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();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compress {}", each.getAbsolutePath());
                LOGGER.error("Details", e);
            } finally {
                IOUtils.closeQuietly(fio);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.info("Error occurs while compress log : {} ", e.getMessage());
        LOGGER.debug("Details", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(fio);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.hbm.devices.scan.ui.android.DeviceZipper.java

static Uri saveAnnounces(@NonNull List<Announce> announces, @NonNull AppCompatActivity activity) {
    final TimeZone tz = TimeZone.getTimeZone("UTC");
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.US);
    df.setTimeZone(tz);/*from   w  w  w . j a v a2  s. c o  m*/
    final String isoDate = df.format(new Date());
    final Charset charSet = Charset.forName("UTF-8");

    try {
        final File file = createFile(activity);
        if (file == null) {
            return null;
        }
        final FileOutputStream fos = new FileOutputStream(file, false);
        final ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
        final ZipEntry entry = new ZipEntry("devices.json");
        zos.putNextEntry(entry);
        zos.write(("{\"date\":\"" + isoDate + "\",").getBytes(charSet));
        zos.write(("\"version\": \"1.0\",").getBytes(charSet));
        zos.write("\"devices\":[".getBytes(charSet));

        final Iterator<Announce> iterator = announces.iterator();
        while (iterator.hasNext()) {
            final Announce announce = iterator.next();
            zos.write(announce.getJSONString().getBytes(charSet));
            if (iterator.hasNext()) {
                zos.write(",\n".getBytes(charSet));
            }
        }

        zos.write("]}".getBytes(charSet));
        zos.closeEntry();
        zos.close();
        fos.close();
        return FileProvider.getUriForFile(activity, "com.hbm.devices.scan.ui.android.fileprovider", file);
    } catch (IOException e) {
        Toast.makeText(activity, activity.getString(R.string.could_not_create, e), Toast.LENGTH_SHORT).show();
        return null;
    }
}

From source file:apim.restful.importexport.utils.ArchiveGeneratorUtil.java

/**
 * Add files of the directory to the archive
 *
 * @param directoryToZip  Location of the archive
 * @param file            File to be included in the archive
 * @param zipOutputStream Output stream//from   w w  w  .  ja va2  s .  c o  m
 * @throws APIExportException If an error occurs while writing files to the archive
 */
private static void addToArchive(File directoryToZip, File file, ZipOutputStream zipOutputStream)
        throws APIExportException {

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(file);

        // Get relative path from archive directory to the specific file
        String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
                file.getCanonicalPath().length());
        if (File.separatorChar != '/')
            zipFilePath = zipFilePath.replace(File.separatorChar,
                    APIImportExportConstants.ARCHIVE_PATH_SEPARATOR);
        ZipEntry zipEntry = new ZipEntry(zipFilePath);
        zipOutputStream.putNextEntry(zipEntry);

        IOUtils.copy(fileInputStream, zipOutputStream);

        zipOutputStream.closeEntry();
    } catch (IOException e) {
        log.error("I/O error while writing files to archive" + e.getMessage());
        throw new APIExportException("I/O error while writing files to archive", e);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:com.nridge.core.base.std.FilUtl.java

/**
 * Compresses the input file into a ZIP file container.
 *
 * @param aInFileName The file name to be compressed.
 * @param aZipFileName The file name of the ZIP container.
 * @throws IOException Related to opening the file streams and
 * related read/write operations./*from   w  ww.  j a v  a2s  .c  o  m*/
 */
static public void zipFile(String aInFileName, String aZipFileName) throws IOException {
    File inFile;
    int byteCount;
    byte[] ioBuf;
    FileInputStream fileIn;
    ZipOutputStream zipOut;
    FileOutputStream fileOut;

    inFile = new File(aInFileName);
    if (inFile.isDirectory())
        return;

    ioBuf = new byte[FILE_IO_BUFFER_SIZE];
    fileIn = new FileInputStream(inFile);
    fileOut = new FileOutputStream(aZipFileName);
    zipOut = new ZipOutputStream(fileOut);
    zipOut.putNextEntry(new ZipEntry(inFile.getName()));
    byteCount = fileIn.read(ioBuf);
    while (byteCount > 0) {
        zipOut.write(ioBuf, 0, byteCount);
        byteCount = fileIn.read(ioBuf);
    }
    fileIn.close();
    zipOut.closeEntry();
    zipOut.close();
}

From source file:gov.nih.nci.caintegrator.common.Cai2Util.java

private static void addFile(File curFile, ZipOutputStream out, int index) throws IOException {
    byte[] tmpBuf = new byte[BUFFER_SIZE];
    FileInputStream in = new FileInputStream(curFile);
    String relativePathName = curFile.getPath().substring(index);
    out.putNextEntry(new ZipEntry(relativePathName));
    int len;//from  ww  w  .j a  v  a  2s . c  o  m
    while ((len = in.read(tmpBuf)) > 0) {
        out.write(tmpBuf, 0, len);
    }
    // Complete the entry
    out.closeEntry();
    in.close();
}

From source file:edu.isi.wings.portal.classes.StorageHandler.java

private static void zipAndStream(File dir, ZipOutputStream zos, String prefix) throws Exception {
    byte bytes[] = new byte[2048];
    for (File file : dir.listFiles()) {
        if (file.isDirectory())
            StorageHandler.zipAndStream(file, zos, prefix + file.getName() + "/");
        else {//  w  ww .ja va2  s  .c  o  m
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            BufferedInputStream bis = new BufferedInputStream(fis);
            zos.putNextEntry(new ZipEntry(prefix + file.getName()));
            int bytesRead;
            while ((bytesRead = bis.read(bytes)) != -1) {
                zos.write(bytes, 0, bytesRead);
            }
            zos.closeEntry();
            bis.close();
            fis.close();
        }
    }
}