List of usage examples for java.util.zip ZipOutputStream close
public void close() throws IOException
From source file:net.sourceforge.squirrel_sql.client.update.UpdateUtilImpl.java
/** * TODO: move to IOUtilities/* ww w. ja v a2 s . c o m*/ * * @see net.sourceforge.squirrel_sql.client.update.UpdateUtil#createZipFile(FileWrapper, FileWrapper[]) */ public void createZipFile(FileWrapper zipFile, FileWrapper... sourceFiles) throws FileNotFoundException, IOException { ZipOutputStream os = new ZipOutputStream(new FileOutputStream(zipFile.getAbsolutePath())); zipFileOs(os, sourceFiles); os.close(); }
From source file:com.pr7.logging.CustomDailyRollingFileAppender.java
/** * Compresses the passed file to a .zip file, stores the .zip in the same * directory as the passed file, and then deletes the original, leaving only * the .zipped archive.//from w ww.j a v a 2 s.c om * * @param file */ private void zipAndDelete(File file) throws IOException { if (!file.getName().endsWith(".zip")) { System.out.println("zipAndDelete file = " + file.getName()); String folderName = "archive"; File folder = new File(file.getParent(), folderName); if (!folder.exists()) { if (folder.mkdir()) { System.out.println("Create " + folderName + " success."); } else { System.out.println("Create " + folderName + " failed."); } } File zipFile = new File(folder, file.getName() + ".zip"); FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry); byte[] buffer = new byte[4096]; while (true) { int bytesRead = fis.read(buffer); if (bytesRead == -1) break; else { zos.write(buffer, 0, bytesRead); } } zos.closeEntry(); fis.close(); zos.close(); file.delete(); } }
From source file:com.l2jserver.service.core.logging.TruncateToZipFileAppender.java
/** * This method creates archive with file instead of deleting it. * //from ww w . ja v a 2 s . c om * @param file * file to truncate */ protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); // Linux systems doesn't provide file creation time, so we have to hope // that log files // were not modified manually after server starup // We can use here Windowns-only solution but that suck :( if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new Error("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new Error("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new Error("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { // not critical error LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { // not critical error fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new Error("Can't delete old log file " + file.getAbsolutePath()); } } }
From source file:com.hazelcast.stabilizer.Utils.java
public static byte[] zip(List<File> roots) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); Deque<File> queue = new LinkedList<File>(); ZipOutputStream zout = new ZipOutputStream(out); Set<String> names = new HashSet<String>(); try {//from w w w . j a v a 2 s . c o m for (File root : roots) { URI base = root.isDirectory() ? root.toURI() : root.getParentFile().toURI(); queue.push(root); while (!queue.isEmpty()) { File file = queue.pop(); if (file.getName().equals(".DS_Store")) { continue; } // log.finest("Zipping: " + file.getAbsolutePath()); if (file.isDirectory()) { String name = base.relativize(file.toURI()).getPath(); name = name.endsWith("/") ? name : name + "/"; if (names.add(name)) { zout.putNextEntry(new ZipEntry(name)); } for (File kid : file.listFiles()) { queue.push(kid); } } else { String name = base.relativize(file.toURI()).getPath(); zout.putNextEntry(new ZipEntry(name)); copy(file, zout); zout.closeEntry(); } } } } finally { zout.close(); } return out.toByteArray(); }
From source file:com.ephesoft.gxt.systemconfig.server.ExportRegexPoolServlet.java
/** * Overridden doGet method.//from w w w . j a v a 2 s.co m */ @Override public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class); final RegexGroupService regexGroupService = this.getSingleBeanOfType(RegexGroupService.class); final List<RegexGroup> regexGroupList = regexGroupService.getRegexGroups(); if (regexGroupList == null) { LOGGER.error("Regex group list is null."); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Regex group list is null."); } else { try { final Calendar cal = Calendar.getInstance(); final String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); final SimpleDateFormat formatter = new SimpleDateFormat(CoreCommonConstant.DATE_FORMAT); final String formattedDate = formatter.format(new Date()); final String zipFileName = StringUtil.concatenate(SystemConfigConstants.REGEX_POOL, CoreCommonConstant.UNDERSCORE, formattedDate, CoreCommonConstant.UNDERSCORE, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.SECOND)); final String tempFolderLocation = StringUtil.concatenate(exportSerailizationFolderPath, File.separator, zipFileName); final File copiedFolder = new File(tempFolderLocation); if (copiedFolder.exists()) { copiedFolder.delete(); } // Setting the parent of regex pattern list to null for exporting RegexUtil.exportRegexPatterns(regexGroupList); // Setting the id of regex group list to "0" for exporting for (final RegexGroup regexGroup : regexGroupList) { regexGroup.setId(0); } copiedFolder.mkdirs(); final File serializedExportFile = new File(tempFolderLocation + File.separator + SystemConfigConstants.REGEX_POOL + SystemConfigConstants.SERIALIZATION_EXT); try { SerializationUtils.serialize((Serializable) regexGroupList, new FileOutputStream(serializedExportFile)); final File originalFolder = new File( StringUtil.concatenate(batchSchemaService.getBaseSampleFDLock(), File.separator, SystemConfigConstants.REGEX_POOL)); if (originalFolder.isDirectory()) { final String[] folderList = originalFolder.list(); Arrays.sort(folderList); } } catch (final FileNotFoundException fileNotFoundException) { // Unable to read serializable file LOGGER.error("Error occurred while creating the serializable file." + fileNotFoundException, fileNotFoundException); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while creating the serializable file."); } resp.setContentType(SystemConfigConstants.APPLICATION_X_ZIP); resp.setHeader(SystemConfigConstants.CONTENT_DISPOSITION, StringUtil.concatenate(SystemConfigConstants.ATTACHMENT_FILENAME, zipFileName, SystemConfigConstants.ZIP_EXT, SystemConfigConstants.HEADER_MODE)); ServletOutputStream out = null; ZipOutputStream zipOutput = null; try { out = resp.getOutputStream(); zipOutput = new ZipOutputStream(out); FileUtils.zipDirectory(tempFolderLocation, zipOutput, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException ioException) { // Unable to create the temporary export file(s)/folder(s) LOGGER.error("Error occurred while creating the zip file." + ioException, ioException); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again."); } finally { // clean up code if (zipOutput != null) { zipOutput.close(); } if (out != null) { out.flush(); } FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder); } } catch (final Exception exception) { LOGGER.error("ERROR IN EXPORT: " + exception, exception); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again."); } } }
From source file:com.aionemu.commons.log4j.appenders.TruncateToZipFileAppender.java
/** * This method creates archive with file instead of deleting it. * * @param file file to truncate//from w w w . j av a 2s. co m */ protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); // Linux systems doesn't provide file creation time, so we have to hope // that log files // were not modified manually after server starup // We can use here Windowns-only solution but that suck :( if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError( "Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { // not critical error LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { // not critical error fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } }
From source file:net.solarnetwork.node.backup.DefaultBackupManager.java
@Override public void exportBackupArchive(String backupKey, OutputStream out) throws IOException { final BackupService service = activeBackupService(); if (service == null) { return;//w w w .ja v a 2 s. co m } final Backup backup = service.backupForKey(backupKey); if (backup == null) { return; } // create the zip archive for the backup files ZipOutputStream zos = new ZipOutputStream(out); try { BackupResourceIterable resources = service.getBackupResources(backup); for (BackupResource r : resources) { zos.putNextEntry(new ZipEntry(r.getBackupPath())); FileCopyUtils.copy(r.getInputStream(), new FilterOutputStream(zos) { @Override public void close() throws IOException { // FileCopyUtils closed the stream, which we don't want here } }); } resources.close(); } finally { zos.flush(); zos.finish(); zos.close(); } }
From source file:com.gatf.executor.report.ReportHandler.java
/** * @param zipFile/* w ww . j ava 2 s. co m*/ * @param directoryToExtractTo Provides file unzip functionality */ public static void zipDirectory(File directory, final String[] fileFilters, String zipFileName) { try { if (!directory.exists() || !directory.isDirectory()) { directory.mkdirs(); logger.info("Invalid Directory provided for zipping..."); return; } File zipFile = new File(directory, zipFileName); FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); File[] files = directory.listFiles(new FilenameFilter() { public boolean accept(File folder, String name) { for (String fileFilter : fileFilters) { return name.toLowerCase().endsWith(fileFilter); } return false; } }); for (File file : files) { FileInputStream fis = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } zos.closeEntry(); fis.close(); } zos.close(); fos.close(); } catch (IOException ioe) { logger.severe(ExceptionUtils.getStackTrace(ioe)); return; } }
From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java
private void addMetaInf(File outputFile, ArrayList<File> jarFiles) throws IOException { File tmp = File.createTempFile(outputFile.getName(), ".add", outputFile.getParentFile()); FileOutputStream fos = new FileOutputStream(tmp); ZipOutputStream zos = new ZipOutputStream(fos); Set<String> entries = new HashSet<String>(); updateWithMetaInf(zos, outputFile, entries, false); for (File f : jarFiles) { updateWithMetaInf(zos, f, entries, true); }//from w ww.j a v a 2 s. com zos.close(); outputFile.delete(); if (!tmp.renameTo(outputFile)) { throw new IOException(String.format("Cannot rename %s to %s", tmp, outputFile.getName())); } }
From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java
public void exportToZip(OutputStream os) throws WPBIOException { ZipOutputStream zos = new ZipOutputStream(os); exportUris(zos, PATH_URIS);/* w w w . j ava2 s . c o m*/ exportSitePages(zos, PATH_SITE_PAGES); exportPageModules(zos, PATH_SITE_PAGES_MODULES); exportMessages(zos, PATH_MESSAGES); exportFiles(zos, PATH_FILES); exportArticles(zos, PATH_ARTICLES); exportGlobals(zos, PATH_GLOBALS); exportLocales(zos, PATH_LOCALES); try { zos.flush(); zos.close(); } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); throw new WPBIOException("Cannot export project, error flushing/closing stream", e); } }