List of usage examples for java.util.zip ZipOutputStream closeEntry
public void closeEntry() throws IOException
From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java
public void addToZipFile(Path file, ZipOutputStream outputStream) throws FileNotFoundException, IOException { // Get file name: example.file String fileName = file.getFileName().toString(); // Create an abstraction for how it will appear in the ZIP file. ZipEntry zipEntry = new ZipEntry(fileName); // Write the file's abstraction into the ZIP file. outputStream.putNextEntry(zipEntry); // Prepare to read the actual file. InputStream inputStream = Files.newInputStream(file); // Buffer the file 4 kilobytes at a time. byte[] bytes = new byte[4096]; // Read the file to its conclusion, writing out the information on the way. int length = 0; while ((length = inputStream.read(bytes)) != -1) outputStream.write(bytes, 0, length); // Close the included file stream. inputStream.close();// w ww .j a va 2s .co m // Close the entry in the ZIP file. outputStream.closeEntry(); }
From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java
public void export(Set<String> fields, MaalrQuery query, File dest) throws IOException, InvalidQueryException, NoIndexAvailableException, BrokenIndexException, InvalidTokenOffsetsException { query.setPageNr(0);//from w w w . j ava 2 s . c om query.setPageSize(50); 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) { QueryResult result = index.query(query, false); if (result == null || result.getEntries() == null || result.getEntries().size() == 0) break; List<LemmaVersion> entries = result.getEntries(); for (LemmaVersion version : entries) { write(writer, version, fields); writer.write("\n"); } query.setPageNr(query.getPageNr() + 1); } writer.flush(); zout.closeEntry(); writer.close(); }
From source file:com.taobao.android.builder.tools.zip.ZipUtils.java
/** * zip//w w w . ja va 2 s. c om * * @param zipFile * @param file * @param destPath * @param overwrite ? * @throws java.io.IOException */ public static void addFileToZipFile(File zipFile, File outZipFile, File file, String destPath, boolean overwrite) throws IOException { byte[] buf = new byte[1024]; ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outZipFile)); ZipEntry entry = zin.getNextEntry(); boolean addFile = true; while (entry != null) { boolean addEntry = true; String name = entry.getName(); if (StringUtils.equalsIgnoreCase(name, destPath)) { if (overwrite) { addEntry = false; } else { addFile = false; } } if (addEntry) { ZipEntry zipEntry = null; if (STORED == entry.getMethod()) { zipEntry = new ZipEntry(entry); } else { zipEntry = new ZipEntry(name); } out.putNextEntry(zipEntry); int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } } entry = zin.getNextEntry(); } if (addFile) { InputStream in = new FileInputStream(file); // Add ZIP entry to output stream. ZipEntry zipEntry = new ZipEntry(destPath); out.putNextEntry(zipEntry); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } // Close the streams zin.close(); out.close(); }
From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java
/** * Creates MimeMessage with supplied values * /* w w w . j a va 2s. c om*/ * @param to - to email address * @param docType - String value for the attached document type * @param subject - Subject for the email * @param instructions - email body * @param content - content to be sent as attachment * @return MimeMessage instance */ public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content, String metadataXMl, String title, String indexBodyToken, String readmeToken) { final MimeMessage msg = mailSender.createMimeMessage(); UUID uniqueID = UUID.randomUUID(); tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID); try { msg.setFrom(new InternetAddress(getFrom())); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // The readable part final MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(instructions); mbp1.setHeader("Content-Type", "text/plain"); // The notification final MimeBodyPart mbp2 = new MimeBodyPart(); final String contentType = "application/xml; charset=UTF-8"; String extension; // HL7 messages should be a txt file, otherwise xml if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) { extension = TXT_EXT; } else { extension = XML_EXT; } final String fileName = docType + UUID.randomUUID() + extension; // final DataSource ds = new AttachmentDS(fileName, content, contentType); // mbp2.setDataHandler(new DataHandler(ds)); /******** START NHIN COMPLIANCE CHANGES *****/ boolean isTempZipFolderCreated = tempZipFolder.mkdirs(); if (!isTempZipFolderCreated) { LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); } String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM")); String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT")); indexFileString = StringUtils.replace(indexFileString, "@document_title@", title); indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString); readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString); // move template files & replace tokens // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false); // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false); // create sub-directories String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01"; File nhinSubDirectory = new File(nhinSubDirectoryPath); boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs(); if (!isNhinSubDirectoryCreated) { LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); } FileOutputStream metadataStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/METADATA.XML")); metadataStream.write(metadataXMl.getBytes()); metadataStream.flush(); metadataStream.close(); FileOutputStream documentStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/DOCUMENT" + extension)); documentStream.write(content.getBytes()); documentStream.flush(); documentStream.close(); String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP"; byte[] buffer = new byte[1024]; // FileOutputStream fos = new FileOutputStream(zipFile); // ZipOutputStream zos = new ZipOutputStream(fos); List<String> fileList = generateFileList(tempZipFolder); ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size()); ZipOutputStream zos = new ZipOutputStream(bout); // LOG.info("File List size: "+fileList.size()); for (String file : fileList) { ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } zos.closeEntry(); // remember close it zos.close(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); mbp2.setDataHandler(new DataHandler(source)); mbp2.setFileName(docType + ".ZIP"); /******** END NHIN COMPLIANCE CHANGES *****/ // mbp2.setFileName(fileName); // mbp2.setHeader("Content-Type", contentType); final Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); msg.setSentDate(new Date()); // FileUtils.deleteDirectory(tempZipFolder); } catch (AddressException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (MessagingException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (IOException e) { LOG.error(e.getMessage()); throw new ApplicationRuntimeException(e.getMessage()); } finally { //reset filelist contents fileList = new ArrayList<String>(); } return msg; }
From source file:com.polyvi.xface.extension.zip.XZipExt.java
/** * ??zip//from w w w .jav a2 s . c o m * * @param srcIs * @param zos * @throws IOException * @throws IllegalArgumentException */ private void writeToZip(InputStream srcIs, ZipOutputStream zos) throws IOException, IllegalArgumentException { if (null == srcIs || null == zos) { XLog.e(CLASS_NAME, "Method writeToZip: param is null!"); throw new IllegalArgumentException(); } try { byte[] readBuffer = new byte[XConstant.BUFFER_LEN]; int bytesIn = 0; bytesIn = srcIs.read(readBuffer); while (bytesIn != -1) { zos.write(readBuffer, 0, bytesIn); bytesIn = srcIs.read(readBuffer); } } catch (IOException e) { XLog.e(CLASS_NAME, "Zip file failed!"); throw new IOException(); } finally { srcIs.close(); zos.closeEntry(); } }
From source file:de.thorstenberger.examServer.webapp.action.PDFBulkExport.java
/** * Call the taskmodel-core-view application via http for every user, that has processed the given task. Streams a zip * archive with all rendered pdf files to <code>os</code>. * * @param tasklets// ww w . j a va 2 s. com * all tasklets to render * @param os * the outputstream the zip shall be written to * @param pdfExporter * @throws IOException */ private void renderAllPdfs(final List<Tasklet> tasklets, final OutputStream os, final PDFExporter pdfExporter) throws IOException { // create zip with all generated pdfs final ZipOutputStream zos = new ZipOutputStream(os); // fetch pdf for every user/tasklet // render a pdf for every user that has a tasklet for the current task for (final Tasklet tasklet : tasklets) { final String userId = tasklet.getUserId(); if (!tasklet.hasOrPassedStatus(Status.INPROGRESS)) { log.info(String.format("Skipping PDF for user %s, last try has no contents.", userId)); continue; } log.debug("exporting pdf for " + userId); // add new zipentry (for next pdf) if (!addGeneratedPDFS(tasklet, userId, zos)) { final String filename = userId + ".pdf"; final ZipEntry ze = new ZipEntry(filename); zos.putNextEntry(ze); // fetch the generated pdf from taskmodel-core-view pdfExporter.renderPdf(tasklet, filename, zos); // close this zipentry zos.closeEntry(); } } zos.close(); }
From source file:link.kjr.file_manager.MainActivity.java
public void createZipFile(String name, final MainActivity activity) { activity.handler.post(new Runnable() { @Override/* ww w . j a va2s .co m*/ public void run() { activity.postMessage(activity.getBaseContext().getString(R.string.creating_zip_file)); } }); try { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(currentPath + "/" + name + ".zip")); for (String file : selectedFiles) { ZipEntry ze = new ZipEntry(file); FileInputStream fis = new FileInputStream(file); zos.putNextEntry(ze); byte[] data = new byte[1024]; int length; while ((length = fis.read(data)) >= 0) { zos.write(data, 0, length); } zos.closeEntry(); fis.close(); } zos.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } activity.handler.post(new Runnable() { @Override public void run() { activity.postMessage(activity.getBaseContext().getString(R.string.done_creating_zip_file)); activity.deselectFiles(); activity.refresh(); } }); }
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];/*from w ww . jav a 2s. 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.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java
/** * Copy zip file and remove ignored files * * @param srcFile//from w w w. j a v a 2 s. c om * @param destFile * @throws IOException */ public void copyZip(final String srcFile, final String destFile) throws Exception { loadDefaultExcludePattern(getRootFolderInZip(srcFile)); final ZipFile zipSrc = new ZipFile(srcFile); final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile)); try { final Enumeration<? extends ZipEntry> entries = zipSrc.entries(); while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); if (!isExcluded(LocalPath.combine(srcFile, entry.getName()), false, srcFile)) { final ZipEntry newEntry = new ZipEntry(entry.getName()); out.putNextEntry(newEntry); final BufferedInputStream in = new BufferedInputStream(zipSrc.getInputStream(entry)); int len; final byte[] buf = new byte[65536]; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } } out.finish(); } catch (final IOException e) { errorMsg = Messages.getString("CreateUploadZipCommand.CopyArchiveErrorMessageFormat"); //$NON-NLS-1$ log.error("Exceptions when copying exising archive ", e); //$NON-NLS-1$ throw e; } finally { out.close(); zipSrc.close(); } }
From source file:nl.nn.adapterframework.soap.Wsdl.java
/** * Generates a zip file (and writes it to the given outputstream), containing the WSDL and all referenced XSD's. * @see #wsdl(java.io.OutputStream, String) */// ww w .jav a2 s . c om public void zip(OutputStream stream, String servletName) throws IOException, ConfigurationException, XMLStreamException, NamingException { ZipOutputStream out = new ZipOutputStream(stream); // First an entry for the WSDL itself: ZipEntry wsdlEntry = new ZipEntry(getFilename() + ".wsdl"); out.putNextEntry(wsdlEntry); wsdl(out, servletName); out.closeEntry(); //And then all XSD's Set<String> entries = new HashSet<String>(); for (XSD xsd : xsds) { String zipName = xsd.getResourceTarget(); if (entries.add(zipName)) { ZipEntry xsdEntry = new ZipEntry(zipName); out.putNextEntry(xsdEntry); XMLStreamWriter writer = WsdlUtils.getWriter(out, false); SchemaUtils.xsdToXmlStreamWriter(xsd, writer); out.closeEntry(); } else { warn("Duplicate xsds in " + this + " " + xsd + " " + xsds); } } out.close(); }