List of usage examples for org.apache.commons.compress.archivers.zip ZipFile close
public void close() throws IOException
From source file:divconq.tool.Updater.java
static public boolean tryUpdate() { @SuppressWarnings("resource") final Scanner scan = new Scanner(System.in); FuncResult<RecordStruct> ldres = Updater.loadDeployed(); if (ldres.hasErrors()) { System.out.println("Error reading deployed.json file: " + ldres.getMessage()); return false; }/*ww w .jav a 2 s .com*/ RecordStruct deployed = ldres.getResult(); String ver = deployed.getFieldAsString("Version"); String packfolder = deployed.getFieldAsString("PackageFolder"); String packprefix = deployed.getFieldAsString("PackagePrefix"); if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) { System.out.println("Error reading deployed.json file: Missing Version or PackageFolder"); return false; } if (StringUtil.isEmpty(packprefix)) packprefix = "DivConq"; System.out.println("Current Version: " + ver); Path packpath = Paths.get(packfolder); if (!Files.exists(packpath) || !Files.isDirectory(packpath)) { System.out.println("Error reading PackageFolder - it may not exist or is not a folder."); return false; } File pp = packpath.toFile(); RecordStruct deployment = null; File matchpack = null; for (File f : pp.listFiles()) { if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip")) continue; System.out.println("Checking: " + f.getName()); // if not a match before, clear this deployment = null; try { ZipFile zf = new ZipFile(f); Enumeration<ZipArchiveEntry> entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); if (entry.getName().equals("deployment.json")) { //System.out.println("crc: " + entry.getCrc()); FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry)); if (pres.hasErrors()) { System.out.println("Error reading deployment.json file"); break; } deployment = (RecordStruct) pres.getResult(); break; } } zf.close(); } catch (IOException x) { System.out.println("Error reading deployment.json file: " + x); } if (deployment != null) { String fndver = deployment.getFieldAsString("Version"); String fnddependson = deployment.getFieldAsString("DependsOn"); if (ver.equals(fnddependson)) { System.out.println("Found update: " + fndver); matchpack = f; break; } } } if ((matchpack == null) || (deployment == null)) { System.out.println("No updates found!"); return false; } String fndver = deployment.getFieldAsString("Version"); String umsg = deployment.getFieldAsString("UpdateMessage"); if (StringUtil.isNotEmpty(umsg)) { System.out.println("========================================================================"); System.out.println(umsg); System.out.println("========================================================================"); } System.out.println(); System.out.println("Do you want to install? (y/n)"); System.out.println(); String p = scan.nextLine().toLowerCase(); if (!p.equals("y")) return false; System.out.println(); System.out.println("Intalling: " + fndver); Set<String> ignorepaths = new HashSet<>(); ListStruct iplist = deployment.getFieldAsList("IgnorePaths"); if (iplist != null) { for (Struct df : iplist.getItems()) ignorepaths.add(df.toString()); } ListStruct dflist = deployment.getFieldAsList("DeleteFiles"); // deleting if (dflist != null) { for (Struct df : dflist.getItems()) { Path delpath = Paths.get(".", df.toString()); if (Files.exists(delpath)) { System.out.println("Deleting: " + delpath.toAbsolutePath()); try { Files.delete(delpath); } catch (IOException x) { System.out.println("Unable to Delete: " + x); } } } } // copying updates System.out.println("Checking for updated files: "); try { @SuppressWarnings("resource") ZipFile zf = new ZipFile(matchpack); Enumeration<ZipArchiveEntry> entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String entryname = entry.getName().replace('\\', '/'); boolean xfnd = false; for (String exculde : ignorepaths) if (entryname.startsWith(exculde)) { xfnd = true; break; } if (xfnd) continue; System.out.print("."); Path localpath = Paths.get(".", entryname); if (entry.isDirectory()) { if (!Files.exists(localpath)) Files.createDirectories(localpath); } else { boolean hashmatch = false; if (Files.exists(localpath)) { String local = null; String update = null; try (InputStream lin = Files.newInputStream(localpath)) { local = HashUtil.getMd5(lin); } try (InputStream uin = zf.getInputStream(entry)) { update = HashUtil.getMd5(uin); } hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update) && local.equals(update)); } if (!hashmatch) { System.out.print("[" + entryname + "]"); try (InputStream uin = zf.getInputStream(entry)) { Files.createDirectories(localpath.getParent()); Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING); } catch (Exception x) { System.out.println("Error updating: " + entryname + " - " + x); return false; } } } } zf.close(); } catch (IOException x) { System.out.println("Error reading update package: " + x); } // updating local config deployed.setField("Version", fndver); OperationResult svres = Updater.saveDeployed(deployed); if (svres.hasErrors()) { System.out.println("Intalled: " + fndver + " but could not update deployed.json. Repair the file before continuing.\nError: " + svres.getMessage()); return false; } System.out.println("Intalled: " + fndver); return true; }
From source file:com.silverpeas.util.ZipManagerTest.java
/** * Test of compressStreamToZip method, of class ZipManager. * * @throws Exception/* w w w . j av a 2 s. c om*/ */ @Test public void testCompressStreamToZip() throws Exception { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("FrenchScrum.odp"); String filePathNameToCreate = separatorChar + "dir1" + separatorChar + "dir2" + separatorChar + "FrenchScrum.odp"; String outfilename = PathTestUtil.TARGET_DIR + "temp" + separatorChar + "testCompressStreamToZip.zip"; ZipManager.compressStreamToZip(inputStream, filePathNameToCreate, outfilename); inputStream.close(); File file = new File(outfilename); assertThat(file, is(notNullValue())); assertThat(file.exists(), is(true)); assertThat(file.isFile(), is(true)); int result = ZipManager.getNbFiles(new File(outfilename)); assertThat(result, is(1)); ZipFile zipFile = new ZipFile(file); assertThat(zipFile.getEntry("/dir1/dir2/FrenchScrum.odp"), is(notNullValue())); zipFile.close(); }
From source file:adams.core.io.ZipUtils.java
/** * Lists the files stored in the ZIP file. * * @param input the ZIP file to obtain the file list from * @param listDirs whether to include directories in the list * @return the stored files//from w w w . ja v a2 s. c om */ public static List<File> listFiles(File input, boolean listDirs) { List<File> result; ZipFile zipfile; Enumeration<ZipArchiveEntry> enm; ZipArchiveEntry entry; result = new ArrayList<>(); zipfile = null; try { zipfile = new ZipFile(input.getAbsoluteFile()); enm = zipfile.getEntries(); while (enm.hasMoreElements()) { entry = enm.nextElement(); // extract if (entry.isDirectory()) { if (listDirs) result.add(new File(entry.getName())); } else { result.add(new File(entry.getName())); } } } catch (Exception e) { e.printStackTrace(); } finally { if (zipfile != null) { try { zipfile.close(); } catch (Exception e) { // ignored } } } return result; }
From source file:mj.ocraptor.extraction.tika.parser.pkg.ZipContainerDetector.java
private static MediaType detectZipFormat(TikaInputStream tis) { try {//from w w w.j ava2 s . com ZipFile zip = new ZipFile(tis.getFile()); // TODO: hasFile()? try { MediaType type = detectOpenDocument(zip); if (type == null) { type = detectOfficeOpenXML(zip, tis); } if (type == null) { type = detectIWork(zip); } if (type == null) { type = detectJar(zip); } if (type == null) { type = detectKmz(zip); } if (type == null) { type = detectIpa(zip); } if (type != null) { return type; } } finally { // TODO: shouldn't we record the open // container so it can be later // reused...? // tis.setOpenContainer(zip); try { zip.close(); } catch (IOException e) { // ignore } } } catch (IOException e) { // ignore } // Fallback: it's still a zip file, we just don't know what kind of one return MediaType.APPLICATION_ZIP; }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Applies the differences in patch to source to create the target file. All binary difference files * are applied to their corresponding file in source using {@link com.nothome.delta.GDiffPatcher}. * All other files listed in <code>META-INF/file.list</code> are copied from patch to output. * * @param patch a zip file created by {@link JarDelta#computeDelta(String, String, ZipFile, ZipFile, ZipArchiveOutputStream)} * containing the patches to apply * @param source the original zip file, where the patches have to be applied * @param output the patched zip file to create * @param list the list//from w w w . j a v a 2 s .co m * @throws IOException if an error occures reading or writing any entry in a zip file */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list) throws IOException { applyDelta(patch, source, output, list, ""); patch.close(); }
From source file:com.hw.util.CompressUtils.java
private static void unzipFolder(File uncompressFile, File descPathFile, boolean override) { ZipFile zipFile = null; try {/*from www . j a v a 2s .c o m*/ zipFile = new ZipFile(uncompressFile, "GBK"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry zipEntry = entries.nextElement(); String name = zipEntry.getName(); name = name.replace("\\", "/"); File currentFile = new File(descPathFile, name); //? if (currentFile.isFile() && currentFile.exists() && !override) { continue; } if (name.endsWith("/")) { currentFile.mkdirs(); continue; } else { currentFile.getParentFile().mkdirs(); } FileOutputStream fos = null; try { fos = new FileOutputStream(currentFile); InputStream is = zipFile.getInputStream(zipEntry); IOUtils.copy(is, fos); } finally { IOUtils.closeQuietly(fos); } } } catch (IOException e) { throw new RuntimeException("", e); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { } } } }
From source file:com.daphne.es.maintain.editor.web.controller.utils.CompressUtils.java
@SuppressWarnings("unchecked") private static void unzipFolder(File uncompressFile, File descPathFile, boolean override) { ZipFile zipFile = null; try {/*from ww w. j ava 2 s . c o m*/ zipFile = new ZipFile(uncompressFile, "GBK"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry zipEntry = entries.nextElement(); String name = zipEntry.getName(); name = name.replace("\\", "/"); File currentFile = new File(descPathFile, name); //? if (currentFile.isFile() && currentFile.exists() && !override) { continue; } if (name.endsWith("/")) { currentFile.mkdirs(); continue; } else { currentFile.getParentFile().mkdirs(); } FileOutputStream fos = null; try { fos = new FileOutputStream(currentFile); InputStream is = zipFile.getInputStream(zipEntry); IOUtils.copy(is, fos); } finally { IOUtils.closeQuietly(fos); } } } catch (IOException e) { throw new RuntimeException("", e); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { } } } }
From source file:com.taobao.android.utils.ZipUtils.java
/** * <p>// w ww .j a v a 2s . com * unzip. * </p> * * @param zipFile a {@link File} object. * @param destination a {@link String} object. * @param encoding a {@link String} object. * @return a {@link List} object. */ public static List<String> unzip(final File zipFile, final String destination, String encoding) { List<String> fileNames = new ArrayList<String>(); String dest = destination; if (!destination.endsWith("/")) { dest = destination + "/"; } ZipFile file; try { file = null; if (null == encoding) file = new ZipFile(zipFile); else file = new ZipFile(zipFile, encoding); Enumeration<ZipArchiveEntry> en = file.getEntries(); ZipArchiveEntry ze = null; while (en.hasMoreElements()) { ze = en.nextElement(); File f = new File(dest, ze.getName()); if (ze.isDirectory()) { f.mkdirs(); continue; } else { f.getParentFile().mkdirs(); InputStream is = file.getInputStream(ze); OutputStream os = new FileOutputStream(f); IOUtils.copy(is, os); is.close(); os.close(); fileNames.add(f.getAbsolutePath()); } } file.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } return fileNames; }
From source file:fr.acxio.tools.agia.tasks.ZipFilesTaskletTest.java
@Test public void testZipFile() throws Exception { String aTargetFilename = "target/Z0-input.zip"; ZipFilesTasklet aTasklet = new ZipFilesTasklet(); aTasklet.setSourceBaseDirectory(new FileSystemResource("src/test/resources/testFiles/")); FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory(); aSourceFactory.setPattern("file:src/test/resources/testFiles/input.csv"); aTasklet.setSourceFactory(aSourceFactory); ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory(); aDestinationFactory.setExpression(aTargetFilename); aTasklet.setDestinationFactory(aDestinationFactory); assertFalse(new File(aTargetFilename).exists()); StepContribution aStepContribution = mock(StepContribution.class); assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null)); verify(aStepContribution, times(1)).incrementReadCount(); verify(aStepContribution, times(1)).incrementWriteCount(1); assertTrue(new File(aTargetFilename).exists()); ZipFile aZipFile = new ZipFile(new File(aTargetFilename)); Enumeration<ZipArchiveEntry> aEntries = aZipFile.getEntries(); assertTrue(aEntries.hasMoreElements()); assertEquals("input.csv", aEntries.nextElement().getName()); assertFalse(aEntries.hasMoreElements()); aZipFile.close(); }
From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java
/** * Tests JarDelta and JarPatcher on two identical files. * * @throws Exception the exception//from w w w . j a va 2 s . c om */ @Test public void testJarPatcherIdentFile() throws Exception { ZipFile originalZip = makeSourceZipFile(sourceFile); new JarDelta().computeDelta(sourceFile.getAbsolutePath(), sourceFile.getAbsolutePath(), originalZip, originalZip, new ZipArchiveOutputStream(new FileOutputStream(patchFile))); ZipFile patch = new ZipFile(patchFile); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { patch.close(); throw new IOException("Invalid patch - list entry 'META-INF/file.list' not found"); } BufferedReader patchlist = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = patchlist.readLine(); String sourceName = next; next = patchlist.readLine(); ZipFile source = new ZipFile(sourceFile); new JarPatcher(patchFile.getName(), sourceName).applyDelta(patch, source, new ZipArchiveOutputStream(new FileOutputStream(resultFile)), patchlist); compareFiles(new ZipFile(sourceFile), new ZipFile(resultFile)); }