List of usage examples for java.util.zip ZipOutputStream putNextEntry
public void putNextEntry(ZipEntry e) throws IOException
From source file:edu.mayo.pipes.iterators.Compressor.java
/** * Create a single entry Zip archive, and prepare it for writing * * @throws IOException/* w w w . j ava2s .co m*/ */ public BufferedWriter makeZipWriter() throws IOException { if (outFile == null) return null; FileOutputStream outFileStream = new FileOutputStream(outFile); ZipOutputStream zipWrite = new ZipOutputStream(outFileStream); ZipEntry zE; // Setup the zip writing things zipWrite.setMethod(ZipOutputStream.DEFLATED); zipWrite.setLevel(9); // Max compression zE = new ZipEntry("Default"); zipWrite.putNextEntry(zE); // Now can attach the writer to write to this zip entry OutputStreamWriter wStream = new OutputStreamWriter(zipWrite); writer = new BufferedWriter(wStream); comp = kZipCompression; return writer; }
From source file:net.solarnetwork.node.backup.FileSystemBackupService.java
@Override public Backup performBackup(final Iterable<BackupResource> resources) { if (resources == null) { return null; }/*from ww w . j a v a 2 s . c o m*/ final Iterator<BackupResource> itr = resources.iterator(); if (!itr.hasNext()) { log.debug("No resources provided, nothing to backup"); return null; } BackupStatus status = setStatusIf(RunningBackup, Configured); if (status != RunningBackup) { return null; } final Calendar now = new GregorianCalendar(); now.set(Calendar.MILLISECOND, 0); final String archiveName = String.format(ARCHIVE_NAME_FORMAT, now); final File archiveFile = new File(backupDir, archiveName); final String archiveKey = getArchiveKey(archiveName); log.info("Starting backup to archive {}", archiveName); log.trace("Backup archive: {}", archiveFile.getAbsolutePath()); Backup backup = null; ZipOutputStream zos = null; try { zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile))); while (itr.hasNext()) { BackupResource r = itr.next(); log.debug("Backup up resource {} to archive {}", r.getBackupPath(), archiveName); zos.putNextEntry(new ZipEntry(r.getBackupPath())); FileCopyUtils.copy(r.getInputStream(), new FilterOutputStream(zos) { @Override public void close() throws IOException { // FileCopyUtils closes the stream, which we don't want } }); } zos.flush(); zos.finish(); log.info("Backup complete to archive {}", archiveName); backup = new SimpleBackup(now.getTime(), archiveKey, archiveFile.length(), true); // clean out older backups File[] backupFiles = getAvailableBackupFiles(); if (backupFiles != null && backupFiles.length > additionalBackupCount + 1) { // delete older files for (int i = additionalBackupCount + 1; i < backupFiles.length; i++) { log.info("Deleting old backup archive {}", backupFiles[i].getName()); if (!backupFiles[i].delete()) { log.warn("Unable to delete backup archive {}", backupFiles[i].getAbsolutePath()); } } } } catch (IOException e) { log.error("IO error creating backup: {}", e.getMessage()); setStatus(Error); } catch (RuntimeException e) { log.error("Error creating backup: {}", e.getMessage()); setStatus(Error); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { // ignore this } } status = setStatusIf(Configured, RunningBackup); if (status != Configured) { // clean up if we encountered an error if (archiveFile.exists()) { archiveFile.delete(); } } } return backup; }
From source file:fr.gael.dhus.datastore.FileSystemDataStore.java
/** * Generates a zip file./*from w w w .j av a2s. c o m*/ * * @param source source file or directory to compress. * @param destination destination of zipped file. * @return the zipped file. */ private void generateZip(File source, File destination) throws IOException { if (source == null || !source.exists()) { throw new IllegalArgumentException("source file should exist"); } if (destination == null) { throw new IllegalArgumentException("destination file should be not null"); } FileOutputStream output = new FileOutputStream(destination); ZipOutputStream zip_out = new ZipOutputStream(output); zip_out.setLevel(cfgManager.getDownloadConfiguration().getCompressionLevel()); List<QualifiedFile> file_list = getFileList(source); byte[] buffer = new byte[BUFFER_SIZE]; for (QualifiedFile qualified_file : file_list) { ZipEntry entry = new ZipEntry(qualified_file.getQualifier()); InputStream input = new FileInputStream(qualified_file.getFile()); int read; zip_out.putNextEntry(entry); while ((read = input.read(buffer)) != -1) { zip_out.write(buffer, 0, read); } input.close(); zip_out.closeEntry(); } zip_out.close(); output.close(); }
From source file:com.qwazr.library.archiver.ArchiverTool.java
public void addToZipFile(final String entryName, final String filePath, final ZipOutputStream zos) throws IOException { final Path srcFile = Paths.get(filePath); if (!Files.exists(srcFile)) throw new FileNotFoundException("The file does not exists: " + srcFile.toAbsolutePath()); try (final InputStream in = Files.newInputStream(srcFile); final BufferedInputStream bIn = new BufferedInputStream(in)) { ZipEntry zipEntry = new ZipEntry(entryName); zos.putNextEntry(zipEntry); IOUtils.copy(bIn, zos);/*w w w . j a v a 2 s .co m*/ zos.closeEntry(); } }
From source file:dpfmanager.shell.modules.server.post.HttpPostHandler.java
private void compressDirectoryToZipfile(String rootDir, String sourceDir, ZipOutputStream out) throws IOException, FileNotFoundException { for (File file : new File(sourceDir).listFiles()) { if (file.isDirectory()) { compressDirectoryToZipfile(rootDir, sourceDir + file.getName() + "/", out); } else {//from ww w .j a v a 2 s . c om ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir, "") + file.getName()); out.putNextEntry(entry); FileInputStream in = new FileInputStream(sourceDir + file.getName()); IOUtils.copy(in, out); IOUtils.closeQuietly(in); } } }
From source file:de.brendamour.jpasskit.signing.PKFileBasedSigningUtil.java
private final void zip(final File directory, final File base, final ZipOutputStream zipOutputStream) throws PKSigningException { File[] files = directory.listFiles(); for (int i = 0, n = files.length; i < n; i++) { if (files[i].isDirectory()) { zip(files[i], base, zipOutputStream); } else {//from w w w . j a va 2 s. co m FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(files[i]); ZipEntry entry = new ZipEntry(getRelativePathOfZipEntry(files[i].getPath(), base.getPath())); zipOutputStream.putNextEntry(entry); IOUtils.copy(fileInputStream, zipOutputStream); } catch (IOException e) { IOUtils.closeQuietly(zipOutputStream); throw new PKSigningException("Error when zipping file", e); } finally { IOUtils.closeQuietly(fileInputStream); } } } }
From source file:au.org.ala.layers.web.UserDataService.java
@RequestMapping(value = WS_USERDATA_SAMPLE, method = { RequestMethod.POST, RequestMethod.GET }) public @ResponseBody void samplezip(HttpServletRequest req, HttpServletResponse resp) { RecordsLookup.setUserDataDao(userDataDao); String id = req.getParameter("q"); String fields = req.getParameter("fl"); String sample = userDataDao.getSampleZip(id, fields); try {//from w w w. jav a 2 s . c o m // Create the ZIP file ZipOutputStream out = new ZipOutputStream(resp.getOutputStream()); //put entry out.putNextEntry(new ZipEntry("sample.csv")); out.write(sample.getBytes()); out.closeEntry(); resp.setContentType("application/zip"); resp.setHeader("Content-Disposition", "attachment; filename=\"sample.zip\""); // Complete the ZIP file out.close(); } catch (Exception e) { logger.error("failed to zip sampling", e); } }
From source file:com.vmware.appfactory.recipe.controller.RecipeApiController.java
private void writeRecipeFileToZip(Recipe recipe, RecipeFile file, ZipOutputStream zos) throws IOException { _log.debug("Writing recipe payload file {}, URI = {}", file.getPath(), file.getURI().toString()); URI uri = file.getURI();/* ww w. jav a2s. c om*/ InputStream is = null; try { zos.putNextEntry(new ZipEntry(file.getPath())); if (uri.getScheme().equals(DsUtil.DATASTORE_URI_SCHEME)) { /* * Use datastore methods to copy the file from the datastore * into the ZIP file. */ Long dsId = Long.valueOf(uri.getHost()); DsDatastore ds = _dsClient.findDatastore(dsId, true); if (ds == null) { throw new URISyntaxException(uri.toString(), "Datastore URI has invalid ID " + uri.getHost()); } is = ds.openStream(uri.getPath()); IOUtils.copy(is, zos); } else { /* * Use regular HTTP methods to copy file from URL into the ZIP file. */ URL url = uri.toURL(); is = new BufferedInputStream(url.openStream()); IOUtils.copy(is, zos); } } catch (URISyntaxException ex) { throwBadLocationException(recipe, uri.toString()); } catch (DsException ex) { throwBadLocationException(recipe, uri.toString()); } catch (MalformedURLException ex) { throwBadLocationException(recipe, uri.toString()); } finally { IOUtils.closeQuietly(is); } }
From source file:com.orange.ocara.model.export.docx.DocxWriter.java
/** * To zip a directory./* ww w. j ava2 s .c o m*/ * * @param rootPath root path * @param directory directory * @param zos ZipOutputStream * @throws IOException */ private void zipDirectory(String rootPath, File directory, ZipOutputStream zos) throws IOException { //get a listing of the directory content File[] files = directory.listFiles(); //loop through dirList, and zip the files for (File file : files) { if (file.isDirectory()) { zipDirectory(rootPath, file, zos); continue; } String filePath = FilenameUtils.normalize(file.getPath(), true); String fileName = StringUtils.difference(rootPath, filePath); fileName = fileName.replaceAll("\\[_\\]", "_").replaceAll("\\[.\\]", "."); //create a FileInputStream on top of file ZipEntry anEntry = new ZipEntry(fileName); zos.putNextEntry(anEntry); FileUtils.copyFile(file, zos); } }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
private byte[] zipDocument(String fileZipName, byte[] content) { logger.debug("IN"); ByteArrayOutputStream bos = null; ZipOutputStream zos = null; ByteArrayInputStream in = null; try {//www . ja v a 2 s . co m bos = new ByteArrayOutputStream(); zos = new ZipOutputStream(bos); ZipEntry ze = new ZipEntry(fileZipName); zos.putNextEntry(ze); in = new ByteArrayInputStream(content); for (int c = in.read(); c != -1; c = in.read()) { zos.write(c); } return bos.toByteArray(); } catch (IOException ex) { logger.error("Error zipping the document", ex); return null; } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { logger.error("Error closing output stream", e); } } if (zos != null) { try { zos.close(); } catch (IOException e) { logger.error("Error closing output stream", e); } } if (in != null) { try { in.close(); } catch (IOException e) { logger.error("Error closing output stream", e); } } } }