List of usage examples for java.util.zip ZipOutputStream putNextEntry
public void putNextEntry(ZipEntry e) throws IOException
From source file:azkaban.common.utils.Utils.java
private static void zipFile(String path, File input, ZipOutputStream zOut) throws IOException { if (input.isDirectory()) { File[] files = input.listFiles(); if (files != null) { for (File f : files) { String childPath = path + input.getName() + (f.isDirectory() ? "/" : ""); zipFile(childPath, f, zOut); }/* w w w .j a va2 s . c om*/ } } else { String childPath = path + (path.length() > 0 ? "/" : "") + input.getName(); ZipEntry entry = new ZipEntry(childPath); zOut.putNextEntry(entry); InputStream fileInputStream = new BufferedInputStream(new FileInputStream(input)); IOUtils.copy(fileInputStream, zOut); fileInputStream.close(); } }
From source file:it.geosolutions.tools.compress.file.Compressor.java
public static File deflate(final File outputDir, final File zipFile, final File[] files, boolean overwrite) { if (zipFile.exists() && overwrite) { if (LOGGER.isInfoEnabled()) LOGGER.info("The output file already exists: " + zipFile + " overvriting"); return zipFile; }/* ww w .j av a 2 s . co m*/ // Create a buffer for reading the files byte[] buf = new byte[Conf.getBufferSize()]; ZipOutputStream out = null; BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(zipFile); bos = new BufferedOutputStream(fos); out = new ZipOutputStream(bos); // Compress the files for (File file : files) { FileInputStream in = null; try { in = new FileInputStream(file); if (file.isDirectory()) { continue; } else { // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(file.getName())); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.flush(); } } finally { try { // Complete the entry out.closeEntry(); } catch (Exception e) { } IOUtils.closeQuietly(in); } } } catch (IOException e) { LOGGER.error(e.getLocalizedMessage(), e); return null; } finally { // Complete the ZIP file IOUtils.closeQuietly(out); IOUtils.closeQuietly(bos); IOUtils.closeQuietly(fos); } return zipFile; }
From source file:com.cenrise.test.azkaban.Utils.java
private static void zipFile(final String path, final File input, final ZipOutputStream zOut) throws IOException { if (input.isDirectory()) { final File[] files = input.listFiles(); if (files != null) { for (final File f : files) { final String childPath = path + input.getName() + (f.isDirectory() ? "/" : ""); zipFile(childPath, f, zOut); }/*from ww w .ja va 2 s. c om*/ } } else { final String childPath = path + (path.length() > 0 ? "/" : "") + input.getName(); final ZipEntry entry = new ZipEntry(childPath); zOut.putNextEntry(entry); final InputStream fileInputStream = new BufferedInputStream(new FileInputStream(input)); try { IOUtils.copy(fileInputStream, zOut); } finally { fileInputStream.close(); } } }
From source file:com.openkm.misc.ZipTest.java
public void testJava() throws IOException { log.debug("testJava()"); File zip = File.createTempFile("java_", ".zip"); // Create zip FileOutputStream fos = new FileOutputStream(zip); ZipOutputStream zos = new ZipOutputStream(fos); zos.putNextEntry(new ZipEntry("coeta")); zos.closeEntry();/*from www . j a v a 2 s . c o m*/ zos.close(); // Read zip FileInputStream fis = new FileInputStream(zip); ZipInputStream zis = new ZipInputStream(fis); ZipEntry ze = zis.getNextEntry(); System.out.println(ze.getName()); assertEquals(ze.getName(), "coeta"); zis.close(); }
From source file:de.xwic.appkit.core.util.ZipUtil.java
/** * Zips the files array into a file that has the name given as parameter. * /* w ww . ja v a 2 s. c o m*/ * @param files * the files array * @param zipFileName * the name for the zip file * @return the new zipped file * @throws IOException */ public static File zip(File[] files, String zipFileName) throws IOException { FileOutputStream stream = null; ZipOutputStream out = null; File archiveFile = null; try { if (!zipFileName.endsWith(".zip")) { zipFileName = zipFileName + ".zip"; } archiveFile = new File(zipFileName); byte buffer[] = new byte[BUFFER_SIZE]; // Open archive file stream = new FileOutputStream(archiveFile); out = new ZipOutputStream(stream); for (int i = 0; i < files.length; i++) { if (null == files[i] || !files[i].exists() || files[i].isDirectory()) { continue; } log.info("Zipping " + files[i].getName()); // Add archive entry ZipEntry zipAdd = new ZipEntry(files[i].getName()); zipAdd.setTime(files[i].lastModified()); out.putNextEntry(zipAdd); // Read input & write to output FileInputStream in = new FileInputStream(files[i]); while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) { break; } out.write(buffer, 0, nRead); } in.close(); } } catch (IOException e) { log.error("Error: " + e.getMessage(), e); throw e; } finally { try { if (null != out) { out.close(); } if (null != stream) { stream.close(); } } catch (IOException e) { log.error("Error: " + e.getMessage(), e); throw e; } } return archiveFile; }
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 w w . ja v a 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:com.taobao.android.builder.tools.zip.ZipUtils.java
/** * ?zip?solib?/*from w w w . java 2 s .co m*/ * * @param output * @param srcDir * @throws Exception */ public static void addFileAndDirectoryToZip(File output, File srcDir) throws Exception { if (output.isDirectory()) { throw new IOException("This is a directory!"); } 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()); 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.jcalvopinam.core.Zipping.java
private static void splitAndZipFile(File inputFile, int bufferSize, CustomFile customFile) throws IOException { int counter = 1; byte[] bufferPart; byte[] buffer = new byte[bufferSize]; File newFile;//from www. jav a 2 s .co m FileInputStream fileInputStream; ZipOutputStream out; String temporalName; String outputFileName; try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile))) { int tmp; System.out.println("Please wait while the file is split:"); while ((tmp = bis.read(buffer)) > 0) { temporalName = String.format("%s.%03d", customFile.getFileName(), counter); newFile = new File(inputFile.getParent(), temporalName); try (FileOutputStream fileOutputStream = new FileOutputStream(newFile)) { fileOutputStream.write(buffer, 0, tmp); } fileInputStream = new FileInputStream(newFile);//file001.zip outputFileName = String.format("%s%s_%03d%s", customFile.getPath(), customFile.getFileName(), counter, Extensions.ZIP.getExtension()); out = new ZipOutputStream(new FileOutputStream(outputFileName)); out.putNextEntry(new ZipEntry(customFile.getFileNameExtension())); bufferPart = new byte[CustomFile.BYTE_SIZE]; int count; while ((count = fileInputStream.read(bufferPart)) > 0) { out.write(bufferPart, 0, count); System.out.print("."); } counter++; fileInputStream.close(); out.close(); FileUtils.deleteQuietly(newFile); } } System.out.println("\nEnded process!"); }
From source file:edu.stanford.epad.plugins.qifpwrapper.QIFPHandler.java
public static File generateZipFile(List<File> files, String dirPath) { File dir_file = new File(dirPath); File zip_file = new File(dirPath + "/temp_" + (fileNum++) + ".zip"); int dir_l = dir_file.getAbsolutePath().length(); FileOutputStream fos = null;/*from w ww .ja v a 2s . c om*/ try { fos = new FileOutputStream(zip_file); } catch (FileNotFoundException e1) { log.warning("File not found", e1); return null; } ZipOutputStream zipout = new ZipOutputStream(fos); zipout.setLevel(1); for (int i = 0; i < files.size(); i++) { File f = (File) files.get(i); if (f.canRead()) { log.info("Adding file: " + f.getAbsolutePath()); try { zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1))); } catch (Exception e) { log.warning("Error adding to zip file", e); return null; } BufferedInputStream fr; try { fr = new BufferedInputStream(new FileInputStream(f)); byte buffer[] = new byte[0xffff]; int b; while ((b = fr.read(buffer)) != -1) zipout.write(buffer, 0, b); fr.close(); zipout.closeEntry(); } catch (Exception e) { log.warning("Error closing zip file", e); return null; } } } try { zipout.finish(); fos.flush(); } catch (IOException e) { e.printStackTrace(); return null; } log.info("file zipped and returning as " + zip_file.getAbsolutePath()); return zip_file; }
From source file:net.minecraftforge.fml.common.asm.transformers.AccessTransformer.java
private static void processJar(File inFile, File outFile, AccessTransformer[] transformers) throws IOException { ZipInputStream inJar = null;// ww w.j av a2s.c om ZipOutputStream outJar = null; try { try { inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile))); } catch (FileNotFoundException e) { throw new FileNotFoundException("Could not open input file: " + e.getMessage()); } try { outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); } catch (FileNotFoundException e) { throw new FileNotFoundException("Could not open output file: " + e.getMessage()); } ZipEntry entry; while ((entry = inJar.getNextEntry()) != null) { if (entry.isDirectory()) { outJar.putNextEntry(entry); continue; } byte[] data = new byte[4096]; ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream(); int len; do { len = inJar.read(data); if (len > 0) { entryBuffer.write(data, 0, len); } } while (len != -1); byte[] entryData = entryBuffer.toByteArray(); String entryName = entry.getName(); if (entryName.endsWith(".class") && !entryName.startsWith(".")) { ClassNode cls = new ClassNode(); ClassReader rdr = new ClassReader(entryData); rdr.accept(cls, 0); String name = cls.name.replace('/', '.').replace('\\', '.'); for (AccessTransformer trans : transformers) { entryData = trans.transform(name, name, entryData); } } ZipEntry newEntry = new ZipEntry(entryName); outJar.putNextEntry(newEntry); outJar.write(entryData); } } finally { IOUtils.closeQuietly(outJar); IOUtils.closeQuietly(inJar); } }