List of usage examples for java.util.zip ZipOutputStream ZipOutputStream
public ZipOutputStream(OutputStream out)
From source file:com.insightml.utils.io.IoUtils.java
public static void zip2(final List<Pair<InputStream, String>> files, final File target) { final byte[] buffer = new byte[1024]; try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target))) { for (final Pair<InputStream, String> file : files) { final ZipEntry ze = new ZipEntry(file.getSecond()); zos.putNextEntry(ze);/* ww w . j a va 2s . com*/ int len; while ((len = file.getFirst().read(buffer)) > 0) { zos.write(buffer, 0, len); } file.getFirst().close(); zos.closeEntry(); } } catch (final IOException e) { throw new IllegalStateException(e); } }
From source file:au.org.ala.layers.grid.GridClassBuilder.java
public static HashMap<Integer, GridClass> buildFromGrid(String filePath) throws IOException { File wktDir = new File(filePath); wktDir.mkdirs();/* w ww. j a va 2 s .c o m*/ int[] wktMap = null; //track values for the SLD ArrayList<Integer> maxValues = new ArrayList<Integer>(); ArrayList<String> labels = new ArrayList<String>(); HashMap<Integer, GridClass> classes = new HashMap<Integer, GridClass>(); Properties p = new Properties(); p.load(new FileReader(filePath + ".txt")); boolean mergeProperties = false; Map<String, Set<Integer>> groupedKeys = new HashMap<String, Set<Integer>>(); Map<Integer, Integer> translateKeys = new HashMap<Integer, Integer>(); Map<String, Integer> translateValues = new HashMap<String, Integer>(); ArrayList<Integer> keys = new ArrayList<Integer>(); for (String key : p.stringPropertyNames()) { try { int k = Integer.parseInt(key); keys.add(k); //grouping of property file keys by value String value = p.getProperty(key); Set<Integer> klist = groupedKeys.get(value); if (klist == null) klist = new HashSet<Integer>(); else mergeProperties = true; klist.add(k); groupedKeys.put(value, klist); if (!translateValues.containsKey(value)) translateValues.put(value, translateValues.size() + 1); translateKeys.put(k, translateValues.get(value)); } catch (NumberFormatException e) { logger.info("Excluding shape key '" + key + "'"); } catch (Exception e) { logger.error(e.getMessage(), e); } } java.util.Collections.sort(keys); Grid g = new Grid(filePath); boolean generateWkt = false; //((long) g.nrows) * ((long) g.ncols) < (long) Integer.MAX_VALUE; if (mergeProperties) { g.replaceValues(translateKeys); if (!new File(filePath + ".txt.old").exists()) FileUtils.moveFile(new File(filePath + ".txt"), new File(filePath + ".txt.old")); StringBuilder sb = new StringBuilder(); for (String value : translateValues.keySet()) { sb.append(translateValues.get(value)).append("=").append(value).append('\n'); } FileUtils.writeStringToFile(new File(filePath + ".txt"), sb.toString()); return buildFromGrid(filePath); } if (generateWkt) { for (String name : groupedKeys.keySet()) { try { Set<Integer> klist = groupedKeys.get(name); String key = klist.iterator().next().toString(); int k = Integer.parseInt(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); if (klist.size() == 1) klist = null; logger.info("getting wkt for " + filePath + " > " + key); Map wktIndexed = Envelope.getGridSingleLayerEnvelopeAsWktIndexed( filePath + "," + key + "," + key, klist, wktMap); //write class wkt File zipFile = new File(filePath + File.separator + key + ".wkt.zip"); ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry(key + ".wkt")); zos.write(((String) wktIndexed.get("wkt")).getBytes()); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream( new FileOutputStream(filePath + File.separator + key + ".wkt")); bos.write(((String) wktIndexed.get("wkt")).getBytes()); bos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (bos != null) { try { bos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("wkt written to file"); gc.setArea_km(SpatialUtil.calculateArea((String) wktIndexed.get("wkt")) / 1000.0 / 1000.0); //store map wktMap = (int[]) wktIndexed.get("map"); //write wkt index FileWriter fw = null; try { fw = new FileWriter(filePath + File.separator + key + ".wkt.index"); fw.append((String) wktIndexed.get("index")); fw.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fw != null) { try { fw.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //write wkt index a binary, include extents (minx, miny, maxx, maxy) and area (sq km) int minPolygonNumber = 0; int maxPolygonNumber = 0; RandomAccessFile raf = null; try { raf = new RandomAccessFile(filePath + File.separator + key + ".wkt.index.dat", "rw"); String[] index = ((String) wktIndexed.get("index")).split("\n"); for (int i = 0; i < index.length; i++) { if (index[i].length() > 1) { String[] cells = index[i].split(","); int polygonNumber = Integer.parseInt(cells[0]); raf.writeInt(polygonNumber); //polygon number int polygonStart = Integer.parseInt(cells[1]); raf.writeInt(polygonStart); //character offset if (i == 0) { minPolygonNumber = polygonNumber; } else if (i == index.length - 1) { maxPolygonNumber = polygonNumber; } } } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (raf != null) { try { raf.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //for SLD maxValues.add(gc.getMaxShapeIdx()); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(minPolygonNumber); gc.setMaxShapeIdx(maxPolygonNumber); logger.info("getting multipolygon for " + filePath + " > " + key); MultiPolygon mp = Envelope.getGridEnvelopeAsMultiPolygon(filePath + "," + key + "," + key); gc.setBbox(mp.getEnvelope().toText().replace(" (", "(").replace(", ", ",")); classes.put(k, gc); try { //write class kml zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".kml.zip")); zos.putNextEntry(new ZipEntry(key + ".kml")); Encoder encoder = new Encoder(new KMLConfiguration()); encoder.setIndenting(true); encoder.encode(mp, KML.Geometry, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("kml written to file"); final SimpleFeatureType TYPE = DataUtilities.createType("class", "the_geom:MultiPolygon,id:Integer,name:String"); FeatureJSON fjson = new FeatureJSON(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); SimpleFeature sf = featureBuilder.buildFeature(null); //write class geojson zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".geojson.zip")); zos.putNextEntry(new ZipEntry(key + ".geojson")); featureBuilder.add(mp); featureBuilder.add(k); featureBuilder.add(name); fjson.writeFeature(sf, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("geojson written to file"); //write class shape file File newFile = new File(filePath + File.separator + key + ".shp"); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", newFile.toURI().toURL()); params.put("create spatial index", Boolean.FALSE); ShapefileDataStore newDataStore = null; try { newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); newDataStore.createSchema(TYPE); newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); Transaction transaction = new DefaultTransaction("create"); String typeName = newDataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName); SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.setTransaction(transaction); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); DefaultFeatureCollection collection = new DefaultFeatureCollection(); collection.addAll(features); featureStore.setTransaction(transaction); features.add(sf); featureStore.addFeatures(collection); transaction.commit(); transaction.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (newDataStore != null) { try { newDataStore.dispose(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".shp.zip")); //add .dbf .shp .shx .prj String[] exts = { ".dbf", ".shp", ".shx", ".prj" }; for (String ext : exts) { zos.putNextEntry(new ZipEntry(key + ext)); FileInputStream fis = null; try { fis = new FileInputStream(filePath + File.separator + key + ext); byte[] buffer = new byte[1024]; int size; while ((size = fis.read(buffer)) > 0) { zos.write(buffer, 0, size); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //remove unzipped files new File(filePath + File.separator + key + ext).delete(); } zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("shape file written to zip"); } catch (Exception e) { logger.error(e.getMessage(), e); } } catch (Exception e) { logger.error(e.getMessage(), e); } } //write polygon mapping g.writeGrid(filePath + File.separator + "polygons", wktMap, g.xmin, g.ymin, g.xmax, g.ymax, g.xres, g.yres, g.nrows, g.ncols); //copy the header file to get it exactly the same, but change the data type copyHeaderAsInt(filePath + ".grd", filePath + File.separator + "polygons.grd"); } else { //build classes without generating polygons Map<Float, float[]> info = new HashMap<Float, float[]>(); for (int j = 0; j < keys.size(); j++) { info.put(keys.get(j).floatValue(), new float[] { 0, Float.NaN, Float.NaN, Float.NaN, Float.NaN }); } g.getClassInfo(info); for (int j = 0; j < keys.size(); j++) { int k = keys.get(j); String key = String.valueOf(k); String name = p.getProperty(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); //for SLD maxValues.add(Integer.valueOf(key)); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(Integer.valueOf(key)); gc.setMaxShapeIdx(Integer.valueOf(key)); float[] stats = info.get(keys.get(j).floatValue()); //only include if area > 0 if (stats[0] > 0) { gc.setBbox("POLYGON((" + stats[1] + " " + stats[2] + "," + stats[1] + " " + stats[4] + "," + stats[3] + " " + stats[4] + "," + stats[3] + " " + stats[2] + "," + stats[1] + " " + stats[2] + "))"); gc.setArea_km((double) stats[0]); classes.put(k, gc); } } } //write sld exportSLD(filePath + File.separator + "polygons.sld", new File(filePath + ".txt").getName(), maxValues, labels); writeProjectionFile(filePath + File.separator + "polygons.prj"); //write .classes.json ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File(filePath + ".classes.json"), classes); return classes; }
From source file:cross.io.misc.WorkflowZipper.java
/** * Saves the currently assigned workflow elements, matching currently * assigned FileFilter to File. Marks all files for deletion on exit. * * @param f the file to save to//from ww w .java 2 s.c o m * @return true if the workflow was zipped, false otherwise * @throws RuntimeException if IOExceptions are encountered */ public boolean save(final File f) { if (this.zipWorkflow) { HashSet<String> zipEntries = new HashSet<>(); final int bufsize = 1024; final File zipFile = f; ZipOutputStream zos; try { final FileOutputStream fos = new FileOutputStream(zipFile); zos = new ZipOutputStream(new BufferedOutputStream(fos)); log.info("Created zip output stream"); final byte[] input_buffer = new byte[bufsize]; File basedir = FileTools.prependDefaultDirsWithPrefix("", null, this.iw.getStartupDate()); if (this.deleteOnExit) { log.info("marked basedir for deletion on exit: {}", basedir); basedir.deleteOnExit(); } if (flatten) { log.info("setting basedir to parent file: {}", basedir.getParentFile()); basedir = basedir.getParentFile(); final Iterator<IWorkflowResult> iter = this.iw.getResults(); while (iter.hasNext()) { final IWorkflowResult iwr = iter.next(); if (iwr instanceof IWorkflowFileResult) { final IWorkflowFileResult iwfr = (IWorkflowFileResult) iwr; final File file = iwfr.getFile(); log.info("Retrieving file result {}", file); // mark file for deletion final File parent = file.getParentFile(); log.info("Retrieving parent of file result {}", parent); // Also delete the parent directory in which file was // contained, // unless it is the base directory + possibly additional // defaultDirs if (parent.getAbsolutePath().startsWith(basedir.getAbsolutePath()) && !parent.getAbsolutePath().equals(basedir.getAbsolutePath())) { log.info("Marking file and parent for deletion"); if (this.deleteOnExit) { parent.deleteOnExit(); file.deleteOnExit(); } } if (file.getAbsolutePath().startsWith(basedir.getAbsolutePath())) { log.info("Marking file for deletion"); if (this.deleteOnExit) { file.deleteOnExit(); } } if ((this.ff != null) && !this.ff.accept(file)) { // Skip file if file filter does not accept it continue; } else { log.info("Adding zip entry!"); addZipEntry(bufsize, zos, input_buffer, file, zipEntries); } } } } else { LinkedList<File> files = new LinkedList<>(Arrays.asList(basedir.listFiles(ff))); File archiveBase = basedir.getParentFile(); while (!files.isEmpty()) { File currentFile = files.removeFirst(); if (currentFile.isDirectory()) { files.addAll(Arrays.asList(currentFile.listFiles(ff))); } else { try { String relativePath = FileTools.getRelativeFile(archiveBase, currentFile).getPath() .replaceAll("\\\\", "/"); log.info("Adding zip entry for {} below {}", relativePath, archiveBase); addRelativeZipEntry(bufsize, zos, input_buffer, relativePath, currentFile, zipEntries); } catch (Exception ex) { log.warn("Caught exception while retrieving relative path:", ex); } } if (this.deleteOnExit) { log.info("Marking file for deletion"); currentFile.deleteOnExit(); } } } try { zos.flush(); zos.close(); } catch (final IOException e) { throw new RuntimeException(e); } } catch (final IOException e) { throw new RuntimeException(e); } return true; } else { log.debug("Configured to not zip Workflow results!"); return false; } }
From source file:com.datasalt.pangool.solr.TupleSolrOutputFormat.java
private static void createZip(File dir, File out) throws IOException { HashSet<File> files = new HashSet<File>(); // take only conf/ and lib/ for (String allowedDirectory : SolrRecordWriter.getAllowedConfigDirectories()) { File configDir = new File(dir, allowedDirectory); boolean configDirExists; /** If the directory does not exist, and is required, bail out */ if (!(configDirExists = configDir.exists()) && SolrRecordWriter.isRequiredConfigDirectory(allowedDirectory)) { throw new IOException(String.format("required configuration directory %s is not present in %s", allowedDirectory, dir)); }/* w w w . j av a 2 s. c om*/ if (!configDirExists) { continue; } listFiles(configDir, files); // Store the files in the existing, allowed // directory configDir, in the list of files // to store in the zip file } out.delete(); int subst = dir.toString().length(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(out)); byte[] buf = new byte[1024]; for (File f : files) { ZipEntry ze = new ZipEntry(f.toString().substring(subst)); zos.putNextEntry(ze); InputStream is = new FileInputStream(f); int cnt; while ((cnt = is.read(buf)) >= 0) { zos.write(buf, 0, cnt); } is.close(); zos.flush(); zos.closeEntry(); } zos.close(); }
From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java
public void export(Set<String> fields, EditorQuery query, File dest) throws NoDatabaseAvailableException, IOException { query.setCurrent(0);//from w w w .j a v a 2 s. c om ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest)); zout.putNextEntry(new ZipEntry("exported.tsv")); OutputStream out = new BufferedOutputStream(zout); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); for (String field : fields) { writer.write(field); writer.write("\t"); } writer.write("\n"); while (true) { LexEntryList result = Database.getInstance().queryForLexEntries(query.getUserOrIp(), query.getRole(), query.getVerification(), query.getVerifier(), query.getStartTime(), query.getEndTime(), query.getState(), query.getPageSize(), query.getCurrent(), query.getSortColumn(), query.isSortAscending()); if (result == null || result.getEntries() == null || result.getEntries().size() == 0) break; for (LexEntry lexEntry : result.entries()) { addUserInfos(lexEntry); LemmaVersion version = lexEntry.getCurrent(); write(writer, version, fields); writer.write("\n"); } query.setCurrent(query.getCurrent() + query.getPageSize()); } writer.flush(); zout.closeEntry(); writer.close(); }
From source file:dpfmanager.shell.interfaces.console.CommonController.java
public String zipFolder(String folder) { try {/*from w w w . j av a 2 s . c om*/ if (!folder.endsWith("/") && !folder.endsWith("\\")) { folder = folder + "/"; } File outputFile = Files.createTempFile("input", ".zip").toFile(); ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile)); compressDirectoryToZipfile(folder, folder, zipFile); IOUtils.closeQuietly(zipFile); return outputFile.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:abfab3d.shapejs.Project.java
public void save(String file) throws IOException { EvaluatedScript escript = m_script.getEvaluatedScript(); Map<String, Parameter> scriptParams = escript.getParamMap(); Gson gson = JSONParsing.getJSONParser(); String code = escript.getCode(); Path workingDirName = Files.createTempDirectory("saveScript"); String workingDirPath = workingDirName.toAbsolutePath().toString(); Map<String, Object> params = new HashMap<String, Object>(); // Write the script to file File scriptFile = new File(workingDirPath + "/main.js"); FileUtils.writeStringToFile(scriptFile, code, "UTF-8"); // Loop through params and create key/pair entries for (Map.Entry<String, Parameter> entry : scriptParams.entrySet()) { String name = entry.getKey(); Parameter pval = entry.getValue(); if (pval.isDefaultValue()) continue; ParameterType type = pval.getType(); switch (type) { case URI: URIParameter urip = (URIParameter) pval; String u = (String) urip.getValue(); // System.out.println("*** uri: " + u); File f = new File(u); String fileName = null; // TODO: This is hacky. If the parameter value is a directory, then assume it was // originally a zip file, and its contents were extracted in the directory. // Search for the zip file in the directory and copy that to the working dir. if (f.isDirectory()) { File[] files = f.listFiles(); for (int i = 0; i < files.length; i++) { String fname = files[i].getName(); if (fname.endsWith(".zip")) { fileName = fname; f = files[i];// w w w .ja v a2 s. c o m } } } else { fileName = f.getName(); } params.put(name, fileName); // Copy the file to working directory FileUtils.copyFile(f, new File(workingDirPath + "/" + fileName), true); break; case LOCATION: LocationParameter lp = (LocationParameter) pval; Vector3d p = lp.getPoint(); Vector3d n = lp.getNormal(); double[] point = { p.x, p.y, p.z }; double[] normal = { n.x, n.y, n.z }; // System.out.println("*** lp: " + java.util.Arrays.toString(point) + ", " + java.util.Arrays.toString(normal)); Map<String, double[]> loc = new HashMap<String, double[]>(); loc.put("point", point); loc.put("normal", normal); params.put(name, loc); break; case AXIS_ANGLE_4D: AxisAngle4dParameter aap = (AxisAngle4dParameter) pval; AxisAngle4d a = (AxisAngle4d) aap.getValue(); params.put(name, a); break; case DOUBLE: DoubleParameter dp = (DoubleParameter) pval; Double d = (Double) dp.getValue(); // System.out.println("*** double: " + d); params.put(name, d); break; case INTEGER: IntParameter ip = (IntParameter) pval; Integer i = ip.getValue(); // System.out.println("*** int: " + pval); params.put(name, i); break; case STRING: StringParameter sp = (StringParameter) pval; String s = sp.getValue(); // System.out.println("*** string: " + s); params.put(name, s); break; case COLOR: ColorParameter cp = (ColorParameter) pval; Color c = cp.getValue(); // System.out.println("*** string: " + s); params.put(name, c.toHEX()); break; case ENUM: EnumParameter ep = (EnumParameter) pval; String e = ep.getValue(); // System.out.println("*** string: " + s); params.put(name, e); break; default: params.put(name, pval); } } if (params.size() > 0) { String paramsJson = gson.toJson(params); File paramFile = new File(workingDirPath + "/" + "params.json"); FileUtils.writeStringToFile(paramFile, paramsJson, "UTF-8"); } File[] files = (new File(workingDirPath)).listFiles(); FileOutputStream fos = new FileOutputStream(file); ZipOutputStream zos = new ZipOutputStream(fos); System.out.println("*** Num files to zip: " + files.length); try { byte[] buffer = new byte[1024]; for (int i = 0; i < files.length; i++) { // if (files[i].getName().endsWith(".zip")) continue; System.out.println("*** Adding file: " + files[i].getName()); FileInputStream fis = new FileInputStream(files[i]); ZipEntry ze = new ZipEntry(files[i].getName()); zos.putNextEntry(ze); int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } fis.close(); } } finally { zos.closeEntry(); zos.close(); } }
From source file:com.ephesoft.dcma.util.FileUtils.java
/** * API to zip list of files to a desired file. Operation aborted if any file is invalid or a directory. * // w w w . j ava 2 s .c o m * @param filePaths {@link List}< {@link String}> * @param outputFilePath {@link String} * @throws IOException in case of error */ public static void zipMultipleFiles(List<String> filePaths, String outputFilePath) throws IOException { LOGGER.info("Zipping files to " + outputFilePath + ".zip file"); File outputFile = new File(outputFilePath); if (outputFile.exists()) { LOGGER.info(outputFilePath + " file already exists. Deleting existing and creating a new file."); outputFile.delete(); } byte[] buffer = new byte[UtilConstants.BUFFER_CONST]; // Create a buffer for copying int bytesRead; ZipOutputStream out = null; FileInputStream input = null; try { out = new ZipOutputStream(new FileOutputStream(outputFilePath)); for (String filePath : filePaths) { LOGGER.info("Writing file " + filePath + " into zip file."); File file = new File(filePath); if (!file.exists() || file.isDirectory()) { throw new Exception("Invalid file: " + file.getAbsolutePath() + ". Either file does not exists or it is a directory."); } input = new FileInputStream(file); // Stream to read file ZipEntry entry = new ZipEntry(file.getName()); // Make a ZipEntry out.putNextEntry(entry); // Store entry bytesRead = input.read(buffer); while (bytesRead != -1) { out.write(buffer, 0, bytesRead); bytesRead = input.read(buffer); } } } catch (Exception e) { LOGGER.error("Exception occured while zipping file." + e.getMessage(), e); } finally { if (input != null) { input.close(); } if (out != null) { out.close(); } } }
From source file:com.webautomation.ScreenCaptureHtmlUnitDriver.java
public static byte[] createZip(Map<String, byte[]> files) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zipfile = new ZipOutputStream(bos); Iterator<String> i = files.keySet().iterator(); String fileName = null;//from w w w.j a va 2 s . c om ZipEntry zipentry = null; while (i.hasNext()) { fileName = i.next(); zipentry = new ZipEntry(fileName); zipfile.putNextEntry(zipentry); zipfile.write(files.get(fileName)); } zipfile.close(); return bos.toByteArray(); }
From source file:S3DataManagerTest.java
@Test public void testZipSourceBuildSpec() throws Exception { clearSourceDirectory();/*from w ww. j a v a 2 s . com*/ String buildSpecName = "Buildspec.yml"; File buildSpec = new File("/tmp/source/" + buildSpecName); String buildSpecContents = "yo\n"; FileUtils.write(buildSpec, buildSpecContents); ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/tmp/source.zip")); S3DataManager dataManager = createDefaultSource(); dataManager.zipSource("/tmp/source/", out, "/tmp/source/"); out.close(); File zip = new File("/tmp/source.zip"); assertTrue(zip.exists()); File unzipFolder = new File("/tmp/folder/"); unzipFolder.mkdir(); ZipFile z = new ZipFile(zip.getPath()); z.extractAll(unzipFolder.getPath()); assertTrue(unzipFolder.list().length == 1); assertEquals(buildSpecName, unzipFolder.list()[0]); File extractedBuildSpec = new File(unzipFolder.getPath() + "/" + buildSpecName); assertTrue(FileUtils.readFileToString(extractedBuildSpec).equals(buildSpecContents)); }