List of usage examples for java.util.zip ZipOutputStream putNextEntry
public void putNextEntry(ZipEntry e) throws IOException
From source file:com.genericworkflownodes.knime.workflowexporter.export.impl.GuseKnimeWorkflowExporter.java
@Override public void export(final Workflow workflow, final File destination) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug(//from www. j a v a 2s . c o m "exporting using " + getShortDescription() + " to [" + destination.getAbsolutePath() + "]"); } final StringBuilder builder = new StringBuilder(); generateWorkflowXml(workflow, builder); final ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(destination)); zipOutputStream.putNextEntry(new ZipEntry("workflow.xml")); zipOutputStream.write(formatXml(builder.toString()).getBytes()); zipOutputStream.closeEntry(); zipOutputStream.close(); }
From source file:ZipSourceCallable.java
public static void zipSource(FilePath workspace, final String directory, final ZipOutputStream out, final String prefixToTrim) throws Exception { if (!Paths.get(directory).startsWith(Paths.get(prefixToTrim))) { throw new Exception(zipSourceError + "prefixToTrim: " + prefixToTrim + ", directory: " + directory); }//from w ww .j a v a 2 s .c om FilePath dir = new FilePath(workspace, directory); List<FilePath> dirFiles = dir.list(); if (dirFiles == null) { throw new Exception("Empty or invalid source directory: " + directory + ". Did you download any source as part of your build?"); } byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0; i < dirFiles.size(); i++) { FilePath f = new FilePath(workspace, dirFiles.get(i).getRemote()); if (f.isDirectory()) { zipSource(workspace, f.getRemote() + File.separator, out, prefixToTrim); } else { InputStream inputStream = f.read(); try { String path = trimPrefix(f.getRemote(), prefixToTrim); if (path.startsWith(File.separator)) { path = path.substring(1, path.length()); } // Zip files created on the windows file system will not unzip // properly on unix systems. Without this change, no directory structure // is built when unzipping. path = path.replace(File.separator, "/"); ZipEntry entry = new ZipEntry(path); out.putNextEntry(entry); while ((bytesRead = inputStream.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } finally { inputStream.close(); } } } }
From source file:com.yifanlu.PSXperiaTool.ZpakCreate.java
public void create(boolean noCompress) throws IOException { Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(), !noCompress);/* w ww . j a v a 2s .c o m*/ IOFileFilter filter = new IOFileFilter() { public boolean accept(File file) { if (file.getName().startsWith(".")) { Logger.debug("Skipping file %s", file.getPath()); return false; } return true; } public boolean accept(File file, String s) { if (s.startsWith(".")) { Logger.debug("Skipping file %s", file.getPath()); return false; } return true; } }; Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE); ZipOutputStream out = new ZipOutputStream(mOut); out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED); while (it.hasNext()) { File current = it.next(); FileInputStream in = new FileInputStream(current); ZipEntry zEntry = new ZipEntry( current.getPath().replace(mDirectory.getPath(), "").substring(1).replace("\\", "/")); if (noCompress) { zEntry.setSize(in.getChannel().size()); zEntry.setCompressedSize(in.getChannel().size()); zEntry.setCrc(getCRC32(current)); } out.putNextEntry(zEntry); Logger.verbose("Adding file %s", current.getPath()); int n; while ((n = in.read(mBuffer)) != -1) { out.write(mBuffer, 0, n); } in.close(); out.closeEntry(); } out.close(); Logger.debug("Done with ZPAK creation."); }
From source file:com.aurel.track.lucene.util.FileUtil.java
private static void zipFiles(File dirZip, ZipOutputStream zipOut, String rootPath) { try {/*w w w . j av a2 s . c o m*/ // get a listing of the directory content File[] dirList = dirZip.listFiles(); byte[] readBuffer = new byte[2156]; int bytesIn; // loop through dirList, and zip the files for (int i = 0; i < dirList.length; i++) { File f = dirList[i]; if (f.isDirectory()) { // if the File object is a directory, call this // function again to add its content recursively String filePath = f.getAbsolutePath(); zipFiles(new File(filePath), zipOut, rootPath); // loop again continue; } // if we reached here, the File object f was not a directory // create a FileInputStream on top of f FileInputStream fis = new FileInputStream(f); // create a new zip entry ZipEntry anEntry = new ZipEntry( f.getAbsolutePath().substring(rootPath.length() + 1, f.getAbsolutePath().length())); // place the zip entry in the ZipOutputStream object zipOut.putNextEntry(anEntry); // now write the content of the file to the ZipOutputStream while ((bytesIn = fis.read(readBuffer)) != -1) { zipOut.write(readBuffer, 0, bytesIn); } // close the Stream fis.close(); } } catch (Exception e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); } }
From source file:com.sqli.liferay.imex.util.xml.ZipUtils.java
private void zipEntries(ZipOutputStream out, File file, File inputDir) throws IOException { String name;/*from w w w . ja v a 2 s . com*/ if (file.equals(inputDir)) { name = ""; } else { name = file.getPath().substring(inputDir.getPath().length() + 1); } if (File.separatorChar == '\\') { name = name.replace("\\", "/"); } log.debug("Adding: " + name); if (file.isDirectory()) { for (File child : file.listFiles()) { zipEntries(out, child, inputDir); } } else { ZipEntry entry = new ZipEntry(name); out.putNextEntry(entry); IOUtils.copy(FileUtils.openInputStream(file), out); } }
From source file:com.esofthead.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java
private void addFileToZip(String path, Content res, ZipOutputStream zip) throws Exception { byte[] buf = new byte[1024]; InputStream contentStream;//from w w w . j a v a 2s. c om if (!res.isExternalResource()) { contentStream = resourceService.getContentStream(res.getPath()); } else { ExternalResourceService service = ResourceUtils.getExternalResourceService(ResourceUtils.getType(res)); contentStream = service.download(ResourceUtils.getExternalDrive(res), res.getPath()); } if (path.length() == 0) path = res.getName(); else path += "/" + res.getName(); zip.putNextEntry(new ZipEntry(path)); int byteLength; while ((byteLength = contentStream.read(buf)) > 0) { zip.write(buf, 0, byteLength); } }
From source file:cascading.tap.hadoop.ZipInputFormatTest.java
public void testSplits() throws Exception { JobConf job = new JobConf(); FileSystem currentFs = FileSystem.get(job); Path file = new Path(workDir, "test.zip"); Reporter reporter = Reporter.NULL;//from w w w . j a va 2s . co m int seed = new Random().nextInt(); LOG.info("seed = " + seed); Random random = new Random(seed); FileInputFormat.setInputPaths(job, file); for (int entries = 1; entries < MAX_ENTRIES; entries += random.nextInt(MAX_ENTRIES / 10) + 1) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(byteArrayOutputStream); long length = 0; LOG.debug("creating; zip file with entries = " + entries); // for each entry in the zip file for (int entryCounter = 0; entryCounter < entries; entryCounter++) { // construct zip entries splitting MAX_LENGTH between entries long entryLength = MAX_LENGTH / entries; ZipEntry zipEntry = new ZipEntry("/entry" + entryCounter + ".txt"); zipEntry.setMethod(ZipEntry.DEFLATED); zos.putNextEntry(zipEntry); for (length = entryCounter * entryLength; length < (entryCounter + 1) * entryLength; length++) { zos.write(Long.toString(length).getBytes()); zos.write("\n".getBytes()); } zos.flush(); zos.closeEntry(); } zos.flush(); zos.close(); currentFs.delete(file, true); OutputStream outputStream = currentFs.create(file); byteArrayOutputStream.writeTo(outputStream); outputStream.close(); ZipInputFormat format = new ZipInputFormat(); format.configure(job); LongWritable key = new LongWritable(); Text value = new Text(); InputSplit[] splits = format.getSplits(job, 100); BitSet bits = new BitSet((int) length); for (int j = 0; j < splits.length; j++) { LOG.debug("split[" + j + "]= " + splits[j]); RecordReader<LongWritable, Text> reader = format.getRecordReader(splits[j], job, reporter); try { int count = 0; while (reader.next(key, value)) { int v = Integer.parseInt(value.toString()); LOG.debug("read " + v); if (bits.get(v)) LOG.warn("conflict with " + v + " in split " + j + " at position " + reader.getPos()); assertFalse("key in multiple partitions.", bits.get(v)); bits.set(v); count++; } LOG.debug("splits[" + j + "]=" + splits[j] + " count=" + count); } finally { reader.close(); } } assertEquals("some keys in no partition.", length, bits.cardinality()); } }
From source file:com.gatf.executor.report.ReportHandler.java
/** * @param zipFile/* w w w . j a v a 2s . c om*/ * @param directoryToExtractTo Provides file unzip functionality */ public static void zipDirectory(File directory, final String[] fileFilters, String zipFileName) { try { if (!directory.exists() || !directory.isDirectory()) { directory.mkdirs(); logger.info("Invalid Directory provided for zipping..."); return; } File zipFile = new File(directory, zipFileName); FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); File[] files = directory.listFiles(new FilenameFilter() { public boolean accept(File folder, String name) { for (String fileFilter : fileFilters) { return name.toLowerCase().endsWith(fileFilter); } return false; } }); for (File file : files) { FileInputStream fis = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } zos.closeEntry(); fis.close(); } zos.close(); fos.close(); } catch (IOException ioe) { logger.severe(ExceptionUtils.getStackTrace(ioe)); return; } }
From source file:net.sourceforge.jweb.maven.mojo.InWarMinifyMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (disabled) return;/*ww w .j a v a 2 s . c o m*/ processConfiguration(); String name = this.getBuilddir().getAbsolutePath() + File.separator + this.getFinalName() + "." + this.getPacking(); this.getLog().info(name); MinifyFileFilter fileFilter = new MinifyFileFilter(); int counter = 0; try { File finalWarFile = new File(name); File tempFile = File.createTempFile(finalWarFile.getName(), null); tempFile.delete();//check deletion boolean renameOk = finalWarFile.renameTo(tempFile); if (!renameOk) { getLog().error("Can not rename file, please check."); } ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile)); ZipFile zipFile = new ZipFile(tempFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); //no compress, just transfer to war if (!fileFilter.accept(entry)) { getLog().debug("nocompress entry: " + entry.getName()); out.putNextEntry(entry); InputStream inputStream = zipFile.getInputStream(entry); byte[] buf = new byte[512]; int len = -1; while ((len = inputStream.read(buf)) > 0) { out.write(buf, 0, len); } inputStream.close(); continue; } File sourceTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp" + File.separator + counter + ".tmp"); File destTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp" + File.separator + counter + ".min.tmp"); FileUtils.writeStringToFile(sourceTmp, ""); FileUtils.writeStringToFile(destTmp, ""); //assemble arguments String[] provied = getYuiArguments(); int length = (provied == null ? 0 : provied.length); length += 5; int i = 0; String[] ret = new String[length]; ret[i++] = "--type"; ret[i++] = (entry.getName().toLowerCase().endsWith(".css") ? "css" : "js"); if (provied != null) { for (String s : provied) { ret[i++] = s; } } ret[i++] = sourceTmp.getAbsolutePath(); ret[i++] = "-o"; ret[i++] = destTmp.getAbsolutePath(); try { InputStream in = zipFile.getInputStream(entry); FileUtils.copyInputStreamToFile(in, sourceTmp); in.close(); YUICompressorNoExit.main(ret); } catch (Exception e) { this.getLog().warn("compress error, this file will not be compressed:" + buildStack(e)); FileUtils.copyFile(sourceTmp, destTmp); } out.putNextEntry(new ZipEntry(entry.getName())); InputStream compressedIn = new FileInputStream(destTmp); byte[] buf = new byte[512]; int len = -1; while ((len = compressedIn.read(buf)) > 0) { out.write(buf, 0, len); } compressedIn.close(); String sourceSize = decimalFormat.format(sourceTmp.length() * 1.0d / 1024) + " KB"; String destSize = decimalFormat.format(destTmp.length() * 1.0d / 1024) + " KB"; getLog().info("compressed entry:" + entry.getName() + " [" + sourceSize + " ->" + destSize + "/" + numberFormat.format(1 - destTmp.length() * 1.0d / sourceTmp.length()) + "]"); counter++; } zipFile.close(); out.close(); FileUtils.cleanDirectory(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp")); FileUtils.forceDelete(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp")); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.mgmtp.jfunk.core.scripting.ModuleArchiver.java
private void zip(final String prefix, final File file, final ZipOutputStream zipOut) throws IOException { if (file.isDirectory()) { String recursePrefix = prefix + file.getName() + '/'; for (File child : file.listFiles()) { zip(recursePrefix, child, zipOut); }/*from ww w .j av a 2 s .com*/ } else { FileInputStream in = null; try { in = new FileInputStream(file); zipOut.putNextEntry(new ZipEntry(prefix + file.getName())); copy(in, zipOut); } finally { closeQuietly(in); zipOut.flush(); zipOut.closeEntry(); } } }