List of usage examples for java.util.zip ZipOutputStream ZipOutputStream
public ZipOutputStream(OutputStream out)
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);//from w w w . ja va 2s . c om 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:ai.serotonin.backup.Backup.java
private void createBackup(final File filename) throws Exception { LOG.info("Creating backup file " + filename); try (final FileOutputStream out = new FileOutputStream(filename); final ZipOutputStream zip = new ZipOutputStream(out)) { final JsonNode files = configRoot.get("files"); for (final JsonNode filesNode : files) { final String prefix = filesNode.get("prefix").asText(); final JsonNode paths = filesNode.get("paths"); for (final JsonNode path : paths) addFile(zip, prefix, path.asText()); }// ww w. j a v a2 s . c om } LOG.info("Created backup file " + filename + ", " + FileUtils.byteCountToDisplaySize(filename.length())); }
From source file:be.neutrinet.ispng.vpn.api.VPNClientConfig.java
@Get public Representation getPKCS11Config() { if (getQueryValue("user") != null && getQueryValue("platform") != null) { String userId = getQueryValue("user"); String platform = getQueryValue("platform"); try {// www .j a v a2 s . c o m User user = Users.dao.queryForId(userId); if (user.certId == null) return clientError("NO_KEYPAIR", Status.CLIENT_ERROR_FAILED_DEPENDENCY); ArrayList<String> config = new ArrayList<>(); config.addAll(Arrays.asList(DEFAULTS)); // create zip ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(baos); Representation res = addPKCS11config(platform.toLowerCase(), config, user); if (res != null) return res; return finalizeZip(config, zip, baos); } catch (Exception ex) { Logger.getLogger(getClass()).debug("Failed to build PKCS11 config for user " + userId, ex); } } return clientError("INVALID_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST); }
From source file:com.diffplug.gradle.ZipMisc.java
/** * Modifies only the specified entries in a zip file. * * @param input a source from a zip file * @param output an output to a zip file * @param toModify a map from path to an input stream for the entries you'd like to change * @param toOmit a set of entries you'd like to leave out of the zip * @throws IOException//ww w . j a va 2s . com */ public static void modify(ByteSource input, ByteSink output, Map<String, Function<byte[], byte[]>> toModify, Predicate<String> toOmit) throws IOException { try (ZipInputStream zipInput = new ZipInputStream(input.openBufferedStream()); ZipOutputStream zipOutput = new ZipOutputStream(output.openBufferedStream())) { while (true) { // read the next entry ZipEntry entry = zipInput.getNextEntry(); if (entry == null) { break; } Function<byte[], byte[]> replacement = toModify.get(entry.getName()); if (replacement != null) { byte[] clean = ByteStreams.toByteArray(zipInput); byte[] modified = replacement.apply(clean); // if it's the entry being modified, enter the modified stuff try (InputStream replacementStream = new ByteArrayInputStream(modified)) { ZipEntry newEntry = new ZipEntry(entry.getName()); newEntry.setComment(entry.getComment()); newEntry.setExtra(entry.getExtra()); newEntry.setMethod(entry.getMethod()); newEntry.setTime(entry.getTime()); zipOutput.putNextEntry(newEntry); copy(replacementStream, zipOutput); } } else if (!toOmit.test(entry.getName())) { // if it isn't being modified, just copy the file stream straight-up ZipEntry newEntry = new ZipEntry(entry); newEntry.setCompressedSize(-1); zipOutput.putNextEntry(newEntry); copy(zipInput, zipOutput); } // close the entries zipInput.closeEntry(); zipOutput.closeEntry(); } } }
From source file:net.firejack.platform.core.utils.ArchiveUtils.java
public static void zip(OutputStream outputStream, Map<String, InputStream> filePaths) throws IOException { ZipOutputStream out = new ZipOutputStream(outputStream); for (Map.Entry<String, InputStream> file : filePaths.entrySet()) { String filename = file.getKey(); InputStream stream = file.getValue(); if (stream != null) { System.out.println("Adding: " + filename); ZipEntry entry = new ZipEntry(filename); out.putNextEntry(entry);/*from w ww . ja va2 s . c o m*/ IOUtils.copy(stream, out); stream.close(); } } out.close(); }
From source file:io.apigee.buildTools.enterprise4g.utils.ZipUtils.java
public void zipDir(File zipFileName, File dirObj, String prefix) throws IOException { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); log.debug("Creating : " + zipFileName); addDir(dirObj, out, dirObj, prefix); out.close();/* ww w .j a v a 2 s .c om*/ }
From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java
/** * Constructor.//from www .j a v a 2 s . c o m * @param out the OutputStream to write aggregated zip output to */ public ZipFileAggregator(OutputStream out) { this.zipOutput = new ZipOutputStream(out); }
From source file:com.mcleodmoores.mvn.natives.UnpackDependenciesMojoTest.java
private static Artifact createArtifact(final File tmp, final String type, final String member) throws IOException { final File zipFile = new File(tmp, type + ".zip"); try (final FileOutputStream out = new FileOutputStream(zipFile)) { final ZipOutputStream zipStream = new ZipOutputStream(out); final ZipEntry license = new ZipEntry("LICENSE"); zipStream.putNextEntry(license); zipStream.write(26);//from w w w.j a v a 2 s . c o m zipStream.closeEntry(); final ZipEntry payload = new ZipEntry(member); zipStream.putNextEntry(payload); zipStream.write(26); zipStream.closeEntry(); zipStream.close(); } final Artifact artifact = Mockito.mock(Artifact.class); Mockito.when(artifact.getType()).thenReturn(type); Mockito.when(artifact.getGroupId()).thenReturn("uk.co.beerdragon"); Mockito.when(artifact.getArtifactId()).thenReturn("test-" + type); Mockito.when(artifact.getVersion()).thenReturn("SNAPSHOT"); Mockito.when(artifact.getFile()).thenReturn(zipFile); return artifact; }
From source file:com.joliciel.csvLearner.CSVEventListWriter.java
public void writeFile(GenericEvents events) { try {/*from w ww .j a v a 2s .c om*/ LOG.debug("writeFile: " + file.getName()); file.delete(); file.createNewFile(); if (file.getName().endsWith(".zip")) isZip = true; Writer writer = null; ZipOutputStream zos = null; try { if (isZip) { zos = new ZipOutputStream(new FileOutputStream(file, false)); writer = new BufferedWriter(new OutputStreamWriter(zos)); } else { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF8")); } Set<String> features = new TreeSet<String>(); if (!filePerEvent) { if (isZip) { zos.putNextEntry(new ZipEntry( file.getName().substring(0, file.getName().lastIndexOf('.')) + ".csv")); } for (GenericEvent event : events) { if (LOG.isTraceEnabled()) LOG.trace("Writing event: " + event.getIdentifier()); for (String feature : event.getFeatures()) { int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER); if (classIndex < 0 || denominalise) features.add(feature); else features.add(feature.substring(0, classIndex)); } } writer.append("ID,"); if (includeOutcomes) writer.append("outcome,"); for (String feature : features) { writer.append(CSVFormatter.format(feature) + ","); } writer.append("\n"); writer.flush(); } for (GenericEvent event : events) { if (filePerEvent) { features = new TreeSet<String>(); for (String feature : event.getFeatures()) { int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER); if (classIndex < 0 || denominalise) features.add(feature); else features.add(feature.substring(0, classIndex)); } if (isZip) zos.putNextEntry(new ZipEntry(event.getIdentifier() + ".csv")); writer.append("ID,"); if (includeOutcomes) writer.append("outcome,"); for (String feature : features) { writer.append(CSVFormatter.format(feature) + ","); } writer.append("\n"); writer.flush(); } writer.append(CSVFormatter.format(identifierPrefix + event.getIdentifier()) + ","); if (includeOutcomes) writer.append(CSVFormatter.format(event.getOutcome()) + ","); for (String feature : features) { Integer featureIndexObj = event.getFeatureIndex(feature); int featureIndex = featureIndexObj == null ? -1 : featureIndexObj.intValue(); if (featureIndex < 0) { writer.append(missingValueString + ","); } else { String eventFeature = event.getFeatures().get(featureIndex); if (!eventFeature.equals(feature)) { int classIndex = eventFeature.indexOf(CSVLearner.NOMINAL_MARKER); String clazz = eventFeature .substring(classIndex + CSVLearner.NOMINAL_MARKER.length()); writer.append(CSVFormatter.format(clazz) + ","); } else { double value = event.getWeights().get(featureIndex); writer.append(CSVFormatter.format(value) + ","); } } } writer.append("\n"); writer.flush(); if (filePerEvent && isZip) zos.closeEntry(); } if (!filePerEvent && isZip) zos.closeEntry(); } finally { if (zos != null) { zos.flush(); zos.close(); } if (writer != null) { writer.flush(); writer.close(); } } } catch (IOException ioe) { throw new RuntimeException(ioe); } }
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;/* w w w .ja v a 2 s.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()); } }