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:Compress.java

/** Zip the contents of the directory, and save it in the zipfile */
public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException {
    // Check that the directory is a directory, and get its contents
    File d = new File(dir);
    if (!d.isDirectory())
        throw new IllegalArgumentException("Compress: not a directory:  " + dir);
    String[] entries = d.list();//from w  ww. j  a  v a2 s  .c o  m
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytes_read;

    // Create a stream to compress data and write it to the zipfile
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

    // Loop through all entries in the directory
    for (int i = 0; i < entries.length; i++) {
        File f = new File(d, entries[i]);
        if (f.isDirectory())
            continue; // Don't zip sub-directories
        FileInputStream in = new FileInputStream(f); // Stream to read file
        ZipEntry entry = new ZipEntry(f.getPath()); // Make a ZipEntry
        out.putNextEntry(entry); // Store entry
        while ((bytes_read = in.read(buffer)) != -1)
            // Copy bytes
            out.write(buffer, 0, bytes_read);
        in.close(); // Close input stream
    }
    // When we're done with the whole loop, close the output stream
    out.close();
}

From source file:com.pieframework.runtime.utils.Zipper.java

public static void zip(String zipFile, Map<String, File> flist) {
    byte[] buf = new byte[1024];
    try {/* w  ww .  j a v a2s .c  om*/
        // Create the ZIP file 
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

        // Compress the files 
        for (String url : flist.keySet()) {
            FileInputStream in = new FileInputStream(flist.get(url).getPath());
            // Add ZIP entry to output stream. Zip entry should be relative
            out.putNextEntry(new ZipEntry(url));
            // Transfer bytes from the file to the ZIP file 
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            // Complete the entry 
            out.closeEntry();
            in.close();
        }

        // Complete the ZIP file 
        out.close();
    } catch (Exception e) {
        throw new RuntimeException("Encountered errors zipping file " + zipFile, e);
    }
}

From source file:net.sourceforge.floggy.maven.ZipUtils.java

/**
 * DOCUMENT ME!//from w w  w .j a  v  a  2s .c  o  m
*
* @param directories DOCUMENT ME!
* @param output DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
*/
public static void zip(File[] directories, File output) throws IOException {
    FileInputStream in = null;
    ZipOutputStream out = null;
    ZipEntry entry = null;

    Collection allFiles = new LinkedList();

    for (int i = 0; i < directories.length; i++) {
        allFiles.addAll(FileUtils.listFiles(directories[i], null, true));
    }

    out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(output)));

    for (Iterator iter = allFiles.iterator(); iter.hasNext();) {
        File temp = (File) iter.next();
        String name = getEntryName(directories, temp.getAbsolutePath());
        entry = new ZipEntry(name);
        out.putNextEntry(entry);

        if (!temp.isDirectory()) {
            in = new FileInputStream(temp);
            IOUtils.copy(in, out);
            in.close();
        }
    }

    out.close();
}

From source file:com.mvdb.etl.actions.ActionUtils.java

public static void zipFullDirectory(String sourceDir, String targetZipFile) {
    FileOutputStream fos = null;//from   w w  w  . j  ava 2 s  .  c  om
    BufferedOutputStream bos = null;
    ZipOutputStream zos = null;

    try {
        fos = new FileOutputStream(targetZipFile);
        bos = new BufferedOutputStream(fos);
        zos = new ZipOutputStream(bos);
        zipDir(sourceDir, new File(sourceDir), zos);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (zos != null) {
            try {
                zos.flush();
                zos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (bos != null) {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

From source file:au.com.jwatmuff.eventmanager.util.ZipUtils.java

public static void zipFolder(File srcFolder, File zipFile, boolean rootFolder) throws IOException {
    ZipOutputStream out = null;
    try {/*from w ww  . j av  a2s.co m*/
        //create ZipOutputStream object
        out = new ZipOutputStream(new FileOutputStream(zipFile));

        String baseName;
        if (rootFolder) {
            //get path prefix so that the zip file does not contain the whole path
            // eg. if folder to be zipped is /home/lalit/test
            // the zip file when opened will have test folder and not home/lalit/test folder
            int len = srcFolder.getAbsolutePath().lastIndexOf(File.separator);
            baseName = srcFolder.getAbsolutePath().substring(0, len + 1);
        } else {
            baseName = srcFolder.getAbsolutePath();
        }

        addFolderToZip(srcFolder, out, baseName);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:de.baumann.thema.RequestActivity.java

private static void createZipFile(final String out_file) {
    final File f = new File(RequestActivity.SAVE_LOC);
    if (!f.canRead() || !f.canWrite()) {
        if (DEBUG)
            Log.d(TAG, RequestActivity.SAVE_LOC + " cannot be compressed due to file permissions");
        return;//  ww w . jav  a  2s . c  om
    }
    try {
        ZipOutputStream zip_out = new ZipOutputStream(
                new BufferedOutputStream(new FileOutputStream(out_file), BUFFER));
        zipFile(RequestActivity.SAVE_LOC, zip_out, "");
        zip_out.close();
    } catch (FileNotFoundException e) {
        if (DEBUG)
            Log.e("File not found", e.getMessage());
    } catch (IOException e) {
        if (DEBUG)
            Log.e("IOException", e.getMessage());
    }
}

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);/* w w w  .  j av a 2 s. co  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: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  w w . j  a va  2s .  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: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.
 * //ww w.ja v  a 2  s  .co  m
 * @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.jaspersoft.studio.community.utils.CommunityAPIUtils.java

/**
 * Creates a ZIP file using the specified zip entries.
 * /*from   www .  j a  v  a 2 s .  c o m*/
 * @param zipEntries the list of entries that will end up in the final zip file
 * @return the zip file reference
 * @throws CommunityAPIException
 */
public static File createZipFile(List<ZipEntry> zipEntries) throws CommunityAPIException {
    String tmpDirectory = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
    String zipFileLocation = tmpDirectory;
    if (!(tmpDirectory.endsWith("/") || tmpDirectory.endsWith("\\"))) { //$NON-NLS-1$ //$NON-NLS-2$
        zipFileLocation += System.getProperty("file.separator"); //$NON-NLS-1$
    }
    zipFileLocation += "issueDetails.zip"; //$NON-NLS-1$

    try {
        // create byte buffer
        byte[] buffer = new byte[1024];
        // create object of FileOutputStream
        FileOutputStream fout = new FileOutputStream(zipFileLocation);
        // create object of ZipOutputStream from FileOutputStream
        ZipOutputStream zout = new ZipOutputStream(fout);

        for (ZipEntry ze : zipEntries) {
            //create object of FileInputStream for source file
            FileInputStream fin = new FileInputStream(ze.getLocation());
            zout.putNextEntry(new java.util.zip.ZipEntry(ze.getLocation()));
            // After creating entry in the zip file, actually write the file.
            int length;
            while ((length = fin.read(buffer)) > 0) {
                zout.write(buffer, 0, length);
            }
            //close the zip entry and related InputStream
            zout.closeEntry();
            fin.close();
        }
        //close the ZipOutputStream
        zout.close();
    } catch (IOException e) {
        throw new CommunityAPIException(Messages.CommunityAPIUtils_ZipCreationError, e);
    }
    return new File(zipFileLocation);
}