List of usage examples for java.util.zip ZipOutputStream close
public void close() throws IOException
From source file:com.taobao.android.builder.tools.zip.ZipUtils.java
/** * zip//from w w w .j a v a 2 s . com * * @param zipFile * @param file * @param destPath * @param overwrite ? * @throws java.io.IOException */ public static void addFileToZipFile(File zipFile, File outZipFile, File file, String destPath, boolean overwrite) throws IOException { byte[] buf = new byte[1024]; ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outZipFile)); ZipEntry entry = zin.getNextEntry(); boolean addFile = true; while (entry != null) { boolean addEntry = true; String name = entry.getName(); if (StringUtils.equalsIgnoreCase(name, destPath)) { if (overwrite) { addEntry = false; } else { addFile = false; } } if (addEntry) { ZipEntry zipEntry = null; if (STORED == entry.getMethod()) { zipEntry = new ZipEntry(entry); } else { zipEntry = new ZipEntry(name); } out.putNextEntry(zipEntry); int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } } entry = zin.getNextEntry(); } if (addFile) { InputStream in = new FileInputStream(file); // Add ZIP entry to output stream. ZipEntry zipEntry = new ZipEntry(destPath); out.putNextEntry(zipEntry); // 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(); } // Close the streams zin.close(); out.close(); }
From source file:com.taobao.android.builder.tools.zip.ZipUtils.java
public static void rezip(File output, File srcDir, Map<String, ZipEntry> zipEntryMethodMap) throws Exception { if (output.isDirectory()) { throw new IOException("This is a directory!"); }//from w w w. j a v a2 s.com if (!output.getParentFile().exists()) { output.getParentFile().mkdirs(); } if (!output.exists()) { output.createNewFile(); } List fileList = getSubFiles(srcDir); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output)); ZipEntry ze = null; byte[] buf = new byte[1024]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File f = (File) fileList.get(i); ze = new ZipEntry(getAbsFileName(srcDir.getPath(), f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); if (zipEntryMethodMap != null) { ZipEntry originEntry = zipEntryMethodMap.get(ze.getName()); if (originEntry != null) { if (originEntry.getMethod() == STORED) { ze.setCompressedSize(f.length()); InputStream in = new BufferedInputStream(new FileInputStream(f)); try { CRC32 crc = new CRC32(); int c; while ((c = in.read()) != -1) { crc.update(c); } ze.setCrc(crc.getValue()); } finally { in.close(); } } ze.setMethod(originEntry.getMethod()); } } zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); while ((readLen = is.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } is.close(); } zos.close(); }
From source file:com.microsoft.tfs.client.common.ui.framework.diagnostics.export.ExportRunnable.java
@Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { error = null;/*w w w.j a v a 2 s.c om*/ errored = false; ZipOutputStream zipout = null; final DataProviderWrapper[] exportableDataProviders = allProvidersCollection.getExportableDataProviders(); final DataProviderCollection exportableCollection = new DataProviderCollection(exportableDataProviders); final DataProviderWrapper[] providersWithExportHandlers = exportableCollection .getDataProvidersWithExportHandlers(); monitor.beginTask(Messages.getString("ExportRunnable.ExportingProgress"), //$NON-NLS-1$ exportableDataProviders.length + providersWithExportHandlers.length); try { final FileOutputStream fos = new FileOutputStream(outputFile); final BufferedOutputStream bos = new BufferedOutputStream(fos); zipout = new ZipOutputStream(bos); processDataProviders(exportableCollection, zipout, monitor); processExportHandlers(providersWithExportHandlers, zipout, monitor); } catch (final Throwable t) { error = t; errored = true; } finally { if (zipout != null) { try { zipout.close(); } catch (final IOException e) { } } cancelled = monitor.isCanceled(); if (cancelled || errored) { outputFile.delete(); } } }
From source file:de.mpg.escidoc.services.exportmanager.Export.java
private void generateArchiveBase(String exportFormat, String archiveFormat, byte[] exportOut, String itemList, File license, BufferedOutputStream bos) throws ExportManagerException, IOException { Utils.checkCondition(!Utils.checkVal(exportFormat) && !(exportOut == null || exportOut.length == 0), "Empty export format"); Utils.checkCondition(!Utils.checkVal(itemList), "Empty item list"); Utils.checkCondition(!Utils.checkVal(archiveFormat), "Empty archive format"); switch (ArchiveFormats.valueOf(archiveFormat)) { case zip:// ww w. j a v a 2 s . co m try { ZipOutputStream zos = new ZipOutputStream(bos); // add export result entry addDescriptionEnrty(exportOut, exportFormat, zos); // add LICENSE AGREEMENT entry addLicenseAgreement(license, zos); // add files to the zip fetchComponentsDo(zos, itemList); zos.close(); } catch (IOException e) { throw new ExportManagerException(e); } break; case tar: try { TarOutputStream tos = new TarOutputStream(bos); // add export result entry addDescriptionEnrty(exportOut, exportFormat, tos); // add LICENSE AGREEMENT entry addLicenseAgreement(license, tos); // add files to the tar fetchComponentsDo(tos, itemList); // logger.info("heapSize after = " + // Runtime.getRuntime().totalMemory()); // logger.info("heapFreeSize after = " + // Runtime.getRuntime().freeMemory()); tos.close(); } catch (IOException e) { throw new ExportManagerException(e); } break; case gzip: try { long ilfs = calculateItemListFileSizes(itemList); long mem = Runtime.getRuntime().freeMemory() / 2; if (ilfs > mem) { logger.info("Generate tar.gz output in tmp file: files' size = " + ilfs + " > Runtime.getRuntime().freeMemory()/2: " + mem); File tar = generateArchiveFile(exportFormat, ArchiveFormats.tar.toString(), exportOut, itemList); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tar)); GZIPOutputStream gzos = new GZIPOutputStream(bos); writeFromStreamToStream(bis, gzos); bis.close(); gzos.close(); tar.delete(); } else { byte[] tar = generateArchive(exportFormat, ArchiveFormats.tar.toString(), exportOut, itemList); BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(tar)); GZIPOutputStream gzos = new GZIPOutputStream(bos); writeFromStreamToStream(bis, gzos); bis.close(); gzos.close(); } } catch (IOException e) { throw new ExportManagerException(e); } break; default: throw new ExportManagerException("Archive format " + archiveFormat + " is not supported"); } }
From source file:fll.subjective.SubjectiveFrame.java
/** * Save out to the same file that things were read in. * //from www.j a va 2 s . co m * @throws IOException if an error occurs writing to the file */ public void save() throws IOException { if (validateData()) { final ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(_file)); final Writer writer = new OutputStreamWriter(zipOut, Utilities.DEFAULT_CHARSET); zipOut.putNextEntry(new ZipEntry("challenge.xml")); XMLUtils.writeXML(_challengeDocument, writer, Utilities.DEFAULT_CHARSET.name()); zipOut.closeEntry(); zipOut.putNextEntry(new ZipEntry("score.xml")); XMLUtils.writeXML(_scoreDocument, writer, Utilities.DEFAULT_CHARSET.name()); zipOut.closeEntry(); zipOut.close(); } }
From source file:com.funambol.framework.tools.FileArchiverTest.java
public void testAddDirectory_NotRecursive() throws Throwable { String sourceDirname = MULTILEVELTREE + File.separator + "first"; String destFilename = BASE_TARGET_DIR + "addedDir.zip"; File destFile = new File(destFilename); if (destFile.exists()) { assertTrue("Unable to delete destination file", destFile.delete()); }/*w ww .j a v a2s . c om*/ // recursively = false, includeRoot = true FileArchiver instance = new FileArchiver(sourceDirname, destFilename, false, true); FileOutputStream outputStream = null; ZipOutputStream zipOutputStream = null; try { outputStream = new FileOutputStream(destFile, false); zipOutputStream = new ZipOutputStream(outputStream); PrivateAccessor.invoke(instance, "addDirectory", new Class[] { ZipOutputStream.class, String.class, File.class }, new Object[] { zipOutputStream, "", new File(sourceDirname) }); assertCounters(instance, 1, 1, 0, 0); assertDestFile(destFile, true); } finally { if (zipOutputStream != null) { zipOutputStream.flush(); zipOutputStream.close(); } if (outputStream != null) { outputStream.flush(); outputStream.close(); } } List<String> expContent = new ArrayList<String>(); expContent.add("first/"); expContent.add("first/firstlog.zip"); assertDestFileContent(destFile, expContent); }
From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java
private void zipUp(File out, File[] in) { FileOutputStream fout = null; ZipOutputStream zout = null; byte[] buffer = new byte[4096]; int bytesRead = 0; try {//w w w. j av a 2s . c o m fout = new FileOutputStream(out); zout = new ZipOutputStream(fout); zout.setMethod(ZipOutputStream.DEFLATED); for (File currFile : in) { FileInputStream fin = new FileInputStream(currFile); ZipEntry currEntry = new ZipEntry(currFile.getName()); zout.putNextEntry(currEntry); while ((bytesRead = fin.read(buffer)) > 0) { zout.write(buffer, 0, bytesRead); } zout.closeEntry(); fin.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { zout.close(); fout.close(); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } } }
From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobFileSavingImpl.java
private Map<String, byte[]> zipFile(ReportExecutionJob job, ReportOutput output, boolean useFolderHierarchy) throws IOException { String attachmentName;//from ww w . ja v a 2s .co m DataContainer attachmentData; if (output.getChildren().isEmpty()) { attachmentName = output.getFilename(); attachmentData = output.getData(); } else { // use zip format attachmentData = job.createDataContainer(); boolean close = true; ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream()); try { zipOut.putNextEntry(new ZipEntry(output.getFilename())); DataContainerStreamUtil.pipeDataAndCloseInput(output.getData().getInputStream(), zipOut); zipOut.closeEntry(); for (Iterator it = output.getChildren().iterator(); it.hasNext();) { ReportOutput child = (ReportOutput) it.next(); String childName = child.getFilename(); if (useFolderHierarchy) childName = getChildrenFolderName(job, output.getFilename()) + '/' + childName; zipOut.putNextEntry(new ZipEntry(childName)); DataContainerStreamUtil.pipeDataAndCloseInput(child.getData().getInputStream(), zipOut); zipOut.closeEntry(); } zipOut.finish(); zipOut.flush(); close = false; zipOut.close(); } catch (IOException e) { throw new JSExceptionWrapper(e); } finally { if (close) { try { zipOut.close(); } catch (IOException e) { log.error("Error closing stream", e); } } } attachmentName = output.getFilename() + ".zip"; } Map result = new HashMap<String, InputStream>(); result.put(attachmentName, IOUtils.toByteArray(attachmentData.getInputStream())); return result; }
From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java
/** * 2jar?,??jar/* www . java2s . c om*/ * @param baseJar * @param diffJar * @param outJar */ public static void unionJar(File baseJar, File diffJar, File outJar) throws IOException { File outParentFolder = outJar.getParentFile(); if (!outParentFolder.exists()) { outParentFolder.mkdirs(); } List<String> diffEntries = getZipEntries(diffJar); FileOutputStream fos = new FileOutputStream(outJar); ZipOutputStream jos = new ZipOutputStream(fos); final byte[] buffer = new byte[8192]; FileInputStream fis = new FileInputStream(baseJar); ZipInputStream zis = new ZipInputStream(fis); try { // loop on the entries of the jar file package and put them in the final jar ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { // do not take directories or anything inside a potential META-INF folder. if (entry.isDirectory()) { continue; } String name = entry.getName(); if (diffEntries.contains(name)) { continue; } JarEntry newEntry; // Preserve the STORED method of the input entry. if (entry.getMethod() == JarEntry.STORED) { newEntry = new JarEntry(entry); } else { // Create a new entry so that the compressed len is recomputed. newEntry = new JarEntry(name); } // add the entry to the jar archive jos.putNextEntry(newEntry); // read the content of the entry from the input stream, and write it into the archive. int count; while ((count = zis.read(buffer)) != -1) { jos.write(buffer, 0, count); } // close the entries for this file jos.closeEntry(); zis.closeEntry(); } } finally { zis.close(); } fis.close(); jos.close(); }
From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java
public static void splitZip(File inputFile, File outputFile, Set<String> includeEnties) throws IOException { if (outputFile.exists()) { FileUtils.deleteQuietly(outputFile); }//from www . j a va2 s . co m if (null == includeEnties || includeEnties.size() < 1) { return; } FileOutputStream fos = new FileOutputStream(outputFile); ZipOutputStream jos = new ZipOutputStream(fos); final byte[] buffer = new byte[8192]; FileInputStream fis = new FileInputStream(inputFile); ZipInputStream zis = new ZipInputStream(fis); try { // loop on the entries of the jar file package and put them in the final jar ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { // do not take directories or anything inside a potential META-INF folder. if (entry.isDirectory()) { continue; } String name = entry.getName(); if (!includeEnties.contains(name)) { continue; } JarEntry newEntry; // Preserve the STORED method of the input entry. if (entry.getMethod() == JarEntry.STORED) { newEntry = new JarEntry(entry); } else { // Create a new entry so that the compressed len is recomputed. newEntry = new JarEntry(name); } // add the entry to the jar archive jos.putNextEntry(newEntry); // read the content of the entry from the input stream, and write it into the archive. int count; while ((count = zis.read(buffer)) != -1) { jos.write(buffer, 0, count); } // close the entries for this file jos.closeEntry(); zis.closeEntry(); } } finally { zis.close(); } fis.close(); jos.close(); }