List of usage examples for java.util.zip ZipOutputStream closeEntry
public void closeEntry() throws IOException
From source file:org.brandroid.openmanager.util.FileManager.java
private void zipIt(OpenPath file, ZipOutputStream zout, int totalSize, String relativePath) throws IOException { byte[] data = new byte[BUFFER]; int read;/*from w w w. ja v a2s .c o m*/ if (file.isFile()) { String name = file.getPath(); if (relativePath != null && name.startsWith(relativePath)) name = name.substring(relativePath.length()); ZipEntry entry = new ZipEntry(name); zout.putNextEntry(entry); BufferedInputStream instream = new BufferedInputStream(file.getInputStream()); //Logger.LogVerbose("zip_folder file name = " + entry.getName()); int size = (int) file.length(); int pos = 0; while ((read = instream.read(data, 0, BUFFER)) != -1) { pos += read; zout.write(data, 0, read); updateProgress(pos, size, totalSize); } zout.closeEntry(); instream.close(); } else if (file.isDirectory()) { //Logger.LogDebug("zip_folder dir name = " + file.getPath()); for (OpenPath kid : file.list()) totalSize += kid.length(); for (OpenPath kid : file.list()) zipIt(kid, zout, totalSize, relativePath); } }
From source file:eionet.meta.exports.ods.Ods.java
/** * Zips file.//from www . j a va 2 s. c o m * * @param fileToZip * file to zip (full path) * @param fileName * file name * @throws java.lang.Exception * if operation fails. */ private void zip(String fileToZip, String fileName) throws Exception { // get source file File src = new File(workingFolderPath + ODS_FILE_NAME); ZipFile zipFile = new ZipFile(src); // create temp file for output File tempDst = new File(workingFolderPath + ODS_FILE_NAME + ".zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempDst)); // iterate on each entry in zip file Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); BufferedInputStream bis; if (StringUtils.equals(fileName, zipEntry.getName())) { bis = new BufferedInputStream(new FileInputStream(new File(fileToZip))); } else { bis = new BufferedInputStream(zipFile.getInputStream(zipEntry)); } ZipEntry ze = new ZipEntry(zipEntry.getName()); zos.putNextEntry(ze); while (bis.available() > 0) { zos.write(bis.read()); } zos.closeEntry(); bis.close(); } zos.finish(); zos.close(); zipFile.close(); // rename file src.delete(); tempDst.renameTo(src); }
From source file:edu.stanford.epad.epadws.handlers.dicom.DownloadUtil.java
public static boolean ZipAndStreamFiles(OutputStream out, List<String> fileNames, String dirPath) { File dir_file = new File(dirPath); int dir_l = dir_file.getAbsolutePath().length(); ZipOutputStream zipout = new ZipOutputStream(out); zipout.setLevel(1);// w w w . j a v a 2s .co m for (int i = 0; i < fileNames.size(); i++) { File f = (File) new File(dirPath + fileNames.get(i)); if (f.canRead()) { log.debug("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 false; } 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 false; } } } try { zipout.finish(); out.flush(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
From source file:org.apache.beam.sdk.io.TextIOTest.java
License:asdf
/** * Create a zip file with the given lines. * * @param expected A list of expected lines, populated in the zip file. * @param filename Optionally zip file name (can be null). * @param fieldsEntries Fields to write in zip entries. * @return The zip filename./*from ww w .ja v a2s . co m*/ * @throws Exception In case of a failure during zip file creation. */ private String createZipFile(List<String> expected, String filename, String[]... fieldsEntries) throws Exception { File tmpFile = tempFolder.resolve(filename).toFile(); String tmpFileName = tmpFile.getPath(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tmpFile)); PrintStream writer = new PrintStream(out, true /* auto-flush on write */); int index = 0; for (String[] entry : fieldsEntries) { out.putNextEntry(new ZipEntry(Integer.toString(index))); for (String field : entry) { writer.println(field); expected.add(field); } out.closeEntry(); index++; } writer.close(); out.close(); return tmpFileName; }
From source file:org.messic.server.api.APISong.java
@Transactional public void getSongsZip(User user, List<Long> desiredSongs, OutputStream os) throws IOException { ZipOutputStream zos = new ZipOutputStream(os); // level - the compression level (0-9) zos.setLevel(9);/*from w w w . java 2 s . c o m*/ HashMap<String, String> songs = new HashMap<String, String>(); for (Long songSid : desiredSongs) { MDOSong song = daoSong.get(user.getLogin(), songSid); if (song != null) { // add file // extract the relative name for entry purpose String entryName = song.getLocation(); if (songs.get(entryName) == null) { // not repeated songs.put(entryName, "ok"); ZipEntry ze = new ZipEntry(entryName); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(song.calculateAbsolutePath(daoSettings.getSettings())); int len; byte buffer[] = new byte[1024]; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); zos.closeEntry(); } } } zos.close(); }
From source file:com.heliosdecompiler.helios.tasks.DecompileAndSaveTask.java
@Override public void run() { File file = FileChooserUtil.chooseSaveLocation(Settings.LAST_DIRECTORY.get().asString(), Collections.singletonList("zip")); if (file == null) return;//from ww w . jav a 2 s .co m if (file.exists()) { boolean delete = SWTUtil.promptForYesNo(Constants.REPO_NAME + " - Overwrite existing file", "The selected file already exists. Overwrite?"); if (!delete) { return; } } AtomicReference<Transformer> transformer = new AtomicReference<>(); Display display = Display.getDefault(); display.asyncExec(() -> { Shell shell = new Shell(Display.getDefault()); FillLayout layout = new FillLayout(); layout.type = SWT.VERTICAL; shell.setLayout(layout); Transformer.getAllTransformers(t -> { return t instanceof Decompiler || t instanceof Disassembler; }).forEach(t -> { Button button = new Button(shell, SWT.RADIO); button.setText(t.getName()); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { transformer.set(t); } }); }); Button ok = new Button(shell, SWT.NONE); ok.setText("OK"); ok.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { shell.close(); shell.dispose(); synchronized (transformer) { transformer.notify(); } } }); shell.pack(); SWTUtil.center(shell); shell.open(); }); synchronized (transformer) { try { transformer.wait(); } catch (InterruptedException e) { ExceptionHandler.handle(e); } } FileOutputStream fileOutputStream = null; ZipOutputStream zipOutputStream = null; try { file.createNewFile(); fileOutputStream = new FileOutputStream(file); zipOutputStream = new ZipOutputStream(fileOutputStream); Set<String> written = new HashSet<>(); for (Pair<String, String> pair : data) { LoadedFile loadedFile = Helios.getLoadedFile(pair.getValue0()); if (loadedFile != null) { String innerName = pair.getValue1(); byte[] bytes = loadedFile.getAllData().get(innerName); if (bytes != null) { if (loadedFile.getClassNode(pair.getValue1()) != null) { StringBuilder buffer = new StringBuilder(); transformer.get().transform(loadedFile.getClassNode(pair.getValue1()), bytes, buffer); String name = innerName.substring(0, innerName.length() - 6) + ".java"; if (written.add(name)) { zipOutputStream.putNextEntry(new ZipEntry(name)); zipOutputStream.write(buffer.toString().getBytes(StandardCharsets.UTF_8)); zipOutputStream.closeEntry(); } else { SWTUtil.showMessage("Duplicate entry occured: " + name); } } else { if (written.add(pair.getValue1())) { zipOutputStream.putNextEntry(new ZipEntry(pair.getValue1())); zipOutputStream.write(loadedFile.getAllData().get(pair.getValue1())); zipOutputStream.closeEntry(); } else { SWTUtil.showMessage("Duplicate entry occured: " + pair.getValue1()); } } } } } } catch (Exception e) { ExceptionHandler.handle(e); } finally { IOUtils.closeQuietly(zipOutputStream); IOUtils.closeQuietly(fileOutputStream); } }
From source file:com.xpn.xwiki.plugin.packaging.Package.java
/** * Write the package.xml file to a ZipOutputStream * /*from w w w.j a va2s .c o m*/ * @param zos the ZipOutputStream to write to * @param context curent XWikiContext * @throws IOException when an error occurs during streaming operation */ private void addInfosToZip(ZipOutputStream zos, XWikiContext context) throws IOException { try { String zipname = DefaultPackageFileName; ZipEntry zipentry = new ZipEntry(zipname); zos.putNextEntry(zipentry); toXML(zos, context); zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } }
From source file:controllers.admin.AuditableController.java
/** * Creates an archive of all the audit logs files and set it into the * personal space of the current user.//from ww w .j a v a 2 s . c o m */ public Promise<Result> exportAuditLogs() { return Promise.promise(new Function0<Result>() { @Override public Result apply() throws Throwable { try { final String currentUserId = getUserSessionManagerPlugin().getUserSessionId(ctx()); final String errorMessage = Msg.get("admin.auditable.export.notification.error.message"); final String successTitle = Msg.get("admin.auditable.export.notification.success.title"); final String successMessage = Msg.get("admin.auditable.export.notification.success.message"); final String notFoundMessage = Msg.get("admin.auditable.export.notification.not_found.message"); final String errorTitle = Msg.get("admin.auditable.export.notification.error.title"); // Audit log export requested if (log.isDebugEnabled()) { log.debug("Audit log export : Audit log export requested by " + currentUserId); } // Execute asynchronously getSysAdminUtils().scheduleOnce(false, "AUDITABLE", Duration.create(0, TimeUnit.MILLISECONDS), new Runnable() { @Override public void run() { // Find the files to be archived String logFilesPathAsString = getConfiguration() .getString("maf.audit.log.location"); File logFilesPath = new File(logFilesPathAsString); File logDirectory = logFilesPath.getParentFile(); if (!logDirectory.exists()) { log.error("Log directory " + logDirectory.getAbsolutePath() + " is not found, please check the configuration"); return; } final String logFilePrefix = (logFilesPath.getName().indexOf('.') != -1 ? logFilesPath.getName().substring(0, logFilesPath.getName().indexOf('.')) : logFilesPath.getName()); if (log.isDebugEnabled()) { log.debug("Audit log export : Selecting files to archive"); } File[] filesToArchive = logDirectory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(logFilePrefix); } }); if (filesToArchive.length != 0) { if (log.isDebugEnabled()) { log.debug("Audit log export : zipping the " + filesToArchive.length + " archive files"); } // Write to the user personal space final String fileName = String.format( "auditExport_%1$td_%1$tm_%1$ty_%1$tH-%1$tM-%1$tS.zip", new Date()); ZipOutputStream out = null; try { OutputStream personalOut = getPersonalStoragePlugin() .createNewFile(currentUserId, fileName); out = new ZipOutputStream(personalOut); for (File fileToArchive : filesToArchive) { ZipEntry e = new ZipEntry(fileToArchive.getName()); out.putNextEntry(e); byte[] data = FileUtils.readFileToByteArray(fileToArchive); out.write(data, 0, data.length); out.closeEntry(); } getNotificationManagerPlugin().sendNotification(currentUserId, NotificationCategory.getByCode(Code.AUDIT), successTitle, successMessage, controllers.my.routes.MyPersonalStorage.index().url()); } catch (Exception e) { log.error("Fail to export the audit archives", e); getNotificationManagerPlugin().sendNotification(currentUserId, NotificationCategory.getByCode(Code.ISSUE), errorTitle, errorMessage, controllers.admin.routes.AuditableController .listAuditable().url()); } finally { IOUtils.closeQuietly(out); } } else { log.error("No audit archive found in the folder"); getNotificationManagerPlugin().sendNotification(currentUserId, NotificationCategory.getByCode(Code.ISSUE), errorTitle, notFoundMessage, controllers.admin.routes.AuditableController.listAuditable().url()); } } }); return ok(Json.newObject()); } catch (Exception e) { return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(), getMessagesPlugin()); } } }); }
From source file:cz.zcu.kiv.eegdatabase.logic.zip.ZipGenerator.java
public File generate(Experiment exp, MetadataCommand mc, Set<DataFile> dataFiles, byte[] licenseFile, String licenseFileName) throws Exception, SQLException, IOException { ZipOutputStream zipOutputStream = null; FileOutputStream fileOutputStream = null; File tempZipFile = null;/*from www . j ava2 s . c om*/ try { log.debug("creating output stream"); // create temp zip file tempZipFile = File.createTempFile("experimentDownload_", ".zip"); // open stream to temp zip file fileOutputStream = new FileOutputStream(tempZipFile); // prepare zip stream zipOutputStream = new ZipOutputStream(fileOutputStream); log.debug("transforming metadata from database to xml file"); OutputStream meta = getTransformer().transformElasticToXml(exp); Scenario scen = exp.getScenario(); log.debug("getting scenario file"); byte[] xmlMetadata = null; if (meta instanceof ByteArrayOutputStream) { xmlMetadata = ((ByteArrayOutputStream) meta).toByteArray(); } ZipEntry entry; if (licenseFileName != null && !licenseFileName.isEmpty()) { zipOutputStream.putNextEntry(entry = new ZipEntry("License/" + licenseFileName)); IOUtils.copyLarge(new ByteArrayInputStream(licenseFile), zipOutputStream); zipOutputStream.closeEntry(); } if (mc.isScenFile() && scen.getScenarioFile() != null) { try { log.debug("saving scenario file (" + scen.getScenarioName() + ") into a zip file"); entry = new ZipEntry("Scenario/" + scen.getScenarioName()); zipOutputStream.putNextEntry(entry); IOUtils.copyLarge(scen.getScenarioFile().getBinaryStream(), zipOutputStream); zipOutputStream.closeEntry(); } catch (Exception ex) { log.error(ex); } } if (xmlMetadata != null) { log.debug("saving xml file of metadata to zip file"); entry = new ZipEntry(getMetadata() + ".xml"); zipOutputStream.putNextEntry(entry); zipOutputStream.write(xmlMetadata); zipOutputStream.closeEntry(); } for (DataFile dataFile : dataFiles) { entry = new ZipEntry(getDataZip() + "/" + dataFile.getFilename()); if (dataFile.getFileContent().length() > 0) { log.debug("saving data file to zip file"); try { zipOutputStream.putNextEntry(entry); } catch (ZipException ex) { String[] partOfName = dataFile.getFilename().split("[.]"); String filename; if (partOfName.length < 2) { filename = partOfName[0] + "" + fileCounter; } else { filename = partOfName[0] + "" + fileCounter + "." + partOfName[1]; } entry = new ZipEntry(getDataZip() + "/" + filename); zipOutputStream.putNextEntry(entry); fileCounter++; } IOUtils.copyLarge(dataFile.getFileContent().getBinaryStream(), zipOutputStream); zipOutputStream.closeEntry(); } } log.debug("returning output stream of zip file"); return tempZipFile; } finally { zipOutputStream.flush(); zipOutputStream.close(); fileOutputStream.flush(); fileOutputStream.close(); fileCounter = 0; } }
From source file:ch.randelshofer.cubetwister.HTMLExporter.java
public void exportToDirectory(String documentName, DocumentModel model, File dir, ProgressObserver p) throws IOException { this.documentName = documentName; this.model = model; this.dir = dir; this.zipFile = null; this.p = p;/*from w w w. j ava2 s . co m*/ init(); processHTMLTemplates(p); new File(dir, "applets").mkdir(); ZipOutputStream zout = new ZipOutputStream( new BufferedOutputStream(new FileOutputStream(new File(dir, "applets/resources.xml.zip")))); zout.setLevel(Deflater.BEST_COMPRESSION); try { //model.writeXML(new PrintWriter(new File(dir, "applets/resources.xml"))); zout.putNextEntry(new ZipEntry("resources.xml")); PrintWriter pw = new PrintWriter(zout); model.writeXML(pw); pw.flush(); zout.closeEntry(); } finally { zout.close(); } p.setProgress(p.getProgress() + 1); }