List of usage examples for java.util.zip ZipOutputStream close
public void close() throws IOException
From source file:com.maxl.java.aips2xml.Aips2Xml.java
static void zipToFile(String dir_name, String file_name) { byte[] buffer = new byte[1024]; try {/* www . j a v a 2 s .c o m*/ FileOutputStream fos = new FileOutputStream(dir_name + changeExtension(file_name, "zip")); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze = new ZipEntry(file_name); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(dir_name + file_name); int len = 0; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); zos.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:csns.web.controller.DownloadController.java
@RequestMapping(value = "/download", params = "assignmentId") public String downloadAssignmentFiles(@RequestParam Long assignmentId, HttpServletResponse response, ModelMap models) throws IOException { Assignment assignment = assignmentDao.getAssignment(assignmentId); String name = assignment.getAlias().replaceAll(replaceRegex, "_"); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=" + name + ".zip"); ZipOutputStream zip = new ZipOutputStream(response.getOutputStream()); for (Submission submission : assignment.getSubmissions()) { String dir = submission.getStudent().getLastName() + "." + submission.getStudent().getFirstName(); addToZip(zip, dir, submission.getFiles()); }//w ww.j a va 2 s. c o m zip.close(); return null; }
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();//from w ww .j a va2s .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.eviware.soapui.impl.wsdl.support.FileAttachment.java
public void setData(byte[] data) { try {//from w ww . ja va 2s. c om // write attachment-data to tempfile ByteArrayOutputStream tempData = new ByteArrayOutputStream(); ZipOutputStream out = new ZipOutputStream(tempData); out.putNextEntry(new ZipEntry(config.getName())); config.setSize(data.length); out.write(data); out.closeEntry(); out.finish(); out.close(); config.setData(tempData.toByteArray()); } catch (Exception e) { SoapUI.logError(e); } }
From source file:com.yunmel.syncretic.utils.io.IOUtils.java
/** * //w w w . j a va 2 s .co m * * @param srcDirName * @param fileName ????*"" * @param descFileName zip */ public static void zipFiles(String srcDirName, String fileName, String descFileName) { // ? if (srcDirName == null) { log.debug(" " + srcDirName + " ?!"); return; } File fileDir = new File(srcDirName); if (!fileDir.exists() || !fileDir.isDirectory()) { log.debug(" " + srcDirName + " ?!"); return; } String dirPath = fileDir.getAbsolutePath(); File descFile = new File(descFileName); try { ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile)); if ("*".equals(fileName) || "".equals(fileName)) { IOUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts); } else { File file = new File(fileDir, fileName); if (file.isFile()) { IOUtils.zipFilesToZipFile(dirPath, file, zouts); } else { IOUtils.zipDirectoryToZipFile(dirPath, file, zouts); } } zouts.close(); log.debug(descFileName + " ?!"); } catch (Exception e) { log.debug("" + e.getMessage()); e.printStackTrace(); } }
From source file:net.duckling.ddl.web.controller.file.BaseAttachController.java
protected void downloadFolder(HttpServletRequest req, HttpServletResponse resp, List<Integer> rids) throws IOException { ZipResourceTree root = new ZipResourceTree(); root.setPath(""); List<Resource> rs = resourceService.getResource(rids); for (Resource r : rs) { if (!r.isPage()) { dealResource(root, r);// w ww. java 2 s. c o m } } String zipName = ""; if (rs.size() == 1) { zipName = rs.get(0).getTitle() + ".zip"; } else { zipName = "?DDL" + rs.get(0).getTitle() + ".zip"; } addDownFolderHeader(req, resp, zipName); ZipOutputStream zipOut = new ZipOutputStream(resp.getOutputStream(), Charset.forName("GBK")); downloadFolder(zipOut, root); zipOut.close(); }
From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java
/** Obtiene el fichero OOXMLK firmado. * @param signatureData/* w ww. j a va 2 s. co m*/ * @return Fichero OOXML firmado * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws TransformerException */ public final byte[] outputSignedOfficeOpenXMLDocument(final byte[] signatureData) throws IOException, ParserConfigurationException, SAXException, TransformerException { final ByteArrayOutputStream signedOOXMLOutputStream = new ByteArrayOutputStream(); final String signatureZipEntryName = "_xmlsignatures/sig-" + UUID.randomUUID().toString() + ".xml"; //$NON-NLS-1$ //$NON-NLS-2$ /* * Copy the original OOXML content to the signed OOXML package. During * copying some files need to changed. */ final ZipOutputStream zipOutputStream = copyOOXMLContent(signatureZipEntryName, signedOOXMLOutputStream); // Add the OOXML XML signature file to the OOXML package. zipOutputStream.putNextEntry(new ZipEntry(signatureZipEntryName)); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); return signedOOXMLOutputStream.toByteArray(); }
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 ww w . j a v a2s . 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:com.aurel.track.admin.customize.category.report.ReportAction.java
/** * Downloads the zip with the template and the other report files *//*from ww w .ja v a 2 s. c o m*/ public String download() { CategoryTokens categoryTokens = CategoryTokens.decodeNode(node); Integer objectID = categoryTokens.getObjectID(); File templateToDownload = ReportBL.getDirTemplate(objectID); servletResponse.reset(); servletResponse.setHeader("Content-Type", "application/zip"); servletResponse.setHeader("Cache-Control", "no-cache"); servletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + templateToDownload.getName() + ".zip" + "\""); ZipOutputStream zipOut; try { ServletOutputStream outs = servletResponse.getOutputStream(); zipOut = new ZipOutputStream(outs); ReportBL.zipFiles(templateToDownload, zipOut, templateToDownload.getAbsolutePath()); zipOut.close(); } catch (FileNotFoundException e) { LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException e) { LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return null; }
From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java
/** * saves a sound package with all meta information and audio files to a ZIP * file and creates the security tokens. * * @param packageFile the zip file, where the soundpackage should be stored * @param soundPackage the sound package info * @throws com.dreikraft.infactory.sound.SoundPackageException encapsulates * all low level (IO) exceptions// www .j av a 2s . com */ public static void exportSoundPackage(final File packageFile, final SoundPackage soundPackage) throws SoundPackageException { if (packageFile == null) { throw new SoundPackageException(new IllegalArgumentException("null package file")); } if (packageFile.delete()) { log.info("successfully deleted file: " + packageFile.getAbsolutePath()); } ZipOutputStream out = null; InputStream in = null; try { out = new ZipOutputStream(new FileOutputStream(packageFile)); out.setLevel(9); // write package info writePackageInfoZipEntry(soundPackage, out); // create path entries ZipEntry soundDir = new ZipEntry(SOUNDS_PATH_PREFIX + SL); out.putNextEntry(soundDir); out.flush(); out.closeEntry(); // write files for (Sound sound : soundPackage.getSounds()) { File axboFile = new File(sound.getAxboFile().getPath()); in = new FileInputStream(axboFile); writeZipEntry(SOUNDS_PATH_PREFIX + SL + axboFile.getName(), out, in); in.close(); } } catch (FileNotFoundException ex) { throw new SoundPackageException(ex); } catch (IOException ex) { throw new SoundPackageException(ex); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { log.error("failed to close ZipOutputStream", ex); } } try { if (in != null) in.close(); } catch (IOException ex) { log.error("failed to close FileInputStream", ex); } } }