List of usage examples for org.apache.commons.compress.archivers.zip ZipFile ZipFile
public ZipFile(String name) throws IOException
From source file:com.android.tradefed.util.Bugreport.java
/** * Return a {@link File} pointing to the bugreport main file. For a flat bugreport, it returns * the flat bugreport itself. For a zipped bugreport, it returns the main entry file. * The returned file is a copy and should be appropriately managed by the user. */// w ww . j a v a 2 s .co m public File getMainFile() { if (mBugreport == null) { return null; } if (!mIsZipped) { return mBugreport; } else { File mainEntry = null; try { try (ZipFile zip = new ZipFile(mBugreport)) { // We get the main_entry.txt that contains the bugreport name. mainEntry = ZipUtil2.extractFileFromZip(zip, "main_entry.txt"); if (mainEntry == null) { CLog.w("main_entry.txt was not found inside the bugreport"); return null; } String bugreportName = FileUtil.readStringFromFile(mainEntry).trim(); CLog.d("bugreport name: '%s'", bugreportName); return ZipUtil2.extractFileFromZip(zip, bugreportName); } } catch (IOException e) { CLog.e("Error while unzipping bugreportz"); CLog.e(e); } finally { FileUtil.deleteFile(mainEntry); } } return null; }
From source file:com.mattc.argus2.concurrent.ZipProcess.java
@Override public void run() { this.running.set(true); // Zip Archive Entry Input Stream InputStream zis = null;/*from ww w . j av a 2s .co m*/ try { this.zip = new ZipFile(this.zipFile); ZipArchiveEntry entry; Enumeration<ZipArchiveEntry> entries; entries = this.zip.getEntriesInPhysicalOrder(); // While there are still Entries to process, iterate while (entries.hasMoreElements()) { entry = entries.nextElement(); // Create the Empty File to Extract to and its Parent Directory // Notify Console and ProgressLog that a File is Being Extracted final File destination = new File(this.destDir, entry.getName()); final File dirs = new File(destination.getParent()); dirs.mkdirs(); Console.info("EXT: " + Utility.relativizePath(destination, this.destDir.getParentFile())); /* * IMPORTANT * * Ensures that All Files have a Directory to go to. * * If a Folder is for some reason created as a File, this will detect * that. It will delete the file and re-create it as a Directory so * that installation can continue. * * If all else fails, print debug information and stop extracting. It * is unlikely the installed application will work without all files * being extracted. */ try { if (!destination.getParentFile().isDirectory()) { if (!destination.getParentFile().delete()) throw new IOException( "Failure to Delete Directory! - " + destination.getCanonicalPath()); destination.getParentFile().mkdirs(); } if (!destination.createNewFile() && !destination.exists()) throw new IOException("Failure to create Destination! - " + destination.getPath()); } catch (final IOException e) { final String errMsg = "Failure to Extract " + this.zipFile.getName(); final String errPath = "PATH = " + destination.getCanonicalPath(); final String errParent = "PARENT = " + destination.getParentFile().getCanonicalPath(); final String errIsDir = "PARENT_IS_DIRECTORY = " + destination.getParentFile().isDirectory(); // Standard IO Error Information e.printStackTrace(System.err); System.err.println(errMsg); System.err.println(errPath); System.err.println(errParent); System.err.println(errIsDir); // Log File Error Information (Possibly Standard IO if DEBUG // = True) Console.exception(e); Console.error(errMsg); Console.error(errPath); Console.error(errParent); Console.error(errIsDir); // Attempt to Delete the Partially Unzipped and // Non-functional install Directory if (!IOUtils.deleteDirectory(this.destDir)) { Console.error("Although extraction failed, the erroneous directory could not be removed!"); } else { Console.info("Erroneous Directory Deleted Successfully!"); } } // Establish a Stream to output data to the destination file zis = this.zip.getInputStream(entry); this.fos = new FileOutputStream(destination); // Read Zip Entry data into buffer, output buffer to // installation file for (int c = zis.read(this.buffer); c > 0; c = zis.read(this.buffer)) { this.fos.write(this.buffer, 0, c); } // Close Current Entry and Destination OutputStream zis.close(); this.fos.close(); } } catch (final ZipException e) { Console.exception(e); } catch (final IOException e) { Console.exception(e); } finally { // Ensure that All Streams Are Closed to prevent Memory // Leaks IOUtils.closeSilently(zis); IOUtils.closeSilently(this.fos); IOUtils.closeSilently(this.zip); this.running.set(false); } }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at * the command line.<br>/*from w w w . j a v a 2 s . com*/ * usage JarPatcher source patch output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { String patchName = null; String outputName = null; String sourceName = null; if (args.length == 0) { System.err.println("usage JarPatcher patch [output [source]]"); System.exit(1); } else { patchName = args[0]; if (args.length > 1) { outputName = args[1]; if (args.length > 2) { sourceName = args[2]; } } } ZipFile patch = new ZipFile(patchName); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { System.err.println("Invalid patch - list entry 'META-INF/file.list' not found"); System.exit(2); } BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = list.readLine(); if (sourceName == null) { sourceName = next; } next = list.readLine(); if (outputName == null) { outputName = next; } int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0")); int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0")); Path sourcePath = Paths.get(sourceName); Path outputPath = Paths.get(outputName); if (ignoreOutputPaths >= outputPath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (") .append(ignoreOutputPaths).append(" in ").append(outputName).append(")"); throw new IOException(b.toString()); } if (ignoreSourcePaths >= sourcePath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (") .append(sourcePath).append(" in ").append(sourceName).append(")"); throw new IOException(b.toString()); } sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); File sourceFile = sourcePath.toFile(); File outputFile = outputPath.toFile(); if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs() || outputFile.getAbsoluteFile().getParentFile().exists())) { patch.close(); throw new IOException("Failed to create " + outputFile.getAbsolutePath()); } new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile), new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list); list.close(); }
From source file:com.mattc.argus.concurrent.ZipProcess.java
public void run() { running.set(true);//from w w w . jav a 2 s . c o m //Zip Archive Entry Input Stream InputStream zis = null; try { zip = new ZipFile(zipFile); ZipArchiveEntry entry; Enumeration<ZipArchiveEntry> entries; entries = zip.getEntriesInPhysicalOrder(); //While there are still Entries to process, iterate while (entries.hasMoreElements()) { entry = entries.nextElement(); //Create the Empty File to Extract to and its Parent Directory //Notify Console and ProgressLog that a File is Being Extracted File destination = new File(destDir, entry.getName()); File dirs = new File(destination.getParent()); dirs.mkdirs(); Console.info("EXT: " + Utility.relativizePath(destination, destDir.getParentFile())); Notifications.updateLog("Extracting " + destination.getName() + (entry.isDirectory() ? " as Directory" : " as File") + "..."); /* * IMPORTANT * * Ensures that All Files have a Directory to go to. * * If a Folder is for some reason created as a File, this will * detect that. It will delete the file and re-create it as a Directory * so that installation can continue. * * If all else fails, print debug information and stop extracting. * It is unlikely the installed application will work without all files * being extracted. */ try { if (!destination.getParentFile().isDirectory()) { destination.getParentFile().delete(); destination.getParentFile().mkdirs(); } destination.createNewFile(); } catch (IOException e) { String errMsg = "Failure to Extract " + zipFile.getName(); String errPath = "PATH = " + destination.getCanonicalPath(); String errParent = "PARENT = " + destination.getParentFile().getCanonicalPath(); String errIsDir = "PARENT_IS_DIRECTORY = " + destination.getParentFile().isDirectory(); //Standard IO Error Information e.printStackTrace(System.err); System.err.println(errMsg); System.err.println(errPath); System.err.println(errParent); System.err.println(errIsDir); //Log File Error Information (Possibly Standard IO if DEBUG = True) Console.exception(e); Console.error(errMsg); Console.error(errPath); Console.error(errParent); Console.error(errIsDir); //GUI Error Information. For End User. String msg = errMsg + "\n" + errPath + "\n" + errParent + "\n" + errIsDir; Notifications.exception(msg, e); //Attempt to Delete the Partially Unzipped and Non-functional install Directory if (!Utility.deleteDirectory(destDir)) { Console.error("Although extraction failed, the erroneous directory could not be removed!"); Notifications.error("Failure to Delete Partially Unzipped Directory!"); } else Console.info("Erroneous Directory Deleted Successfully!"); } //Establish a Stream to output data to the destination file zis = zip.getInputStream(entry); fos = new FileOutputStream(destination); //Read Zip Entry data into buffer, output buffer to installation file for (int c = zis.read(buffer); c > 0; c = zis.read(buffer)) fos.write(buffer, 0, c); //Close Current Entry and Destination OutputStream zis.close(); fos.close(); } } catch (ZipException e) { Console.exception(e); } catch (IOException e) { Console.exception(e); } finally { //Ensure that All Streams Are Closed to prevent Memory Leaks Utility.closeStream(zis); Utility.closeStream(fos); Utility.closeStream(zip); running.set(false); } }
From source file:com.android.tradefed.util.ZipUtil2Test.java
@Test public void testExtractZip() throws Exception { final File zip = getTestDataFile("permission-test"); final File destDir = createTempDir("ZipUtil2Test"); ZipFile zipFile = null;/*from ww w .j ava2 s . co m*/ try { zipFile = new ZipFile(zip); ZipUtil2.extractZip(zipFile, destDir); // now loop over files to verify for (File file : destDir.listFiles()) { // the pmierssion-test.zip file has no hierarchy inside verifyFilePermission(file); } } finally { ZipFile.closeQuietly(zipFile); } }
From source file:es.ucm.fdi.util.archive.ZipFormat.java
public void expand(File source, File destDir) throws IOException { assertIsZip(source);/*ww w.j a v a2s .c o m*/ try (ZipFile zf = new ZipFile(source)) { byte[] b = new byte[512]; Enumeration entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry e = (ZipArchiveEntry) entries.nextElement(); //log.debug("Extracting zip: "+ficheroZip.getName()); // baskslash-protection: zip format expects only 'fw' slashes String name = FileUtils.toCanonicalPath(e.getName()); if (e.isDirectory()) { //log.debug("\tExtracting directory "+e.getName()); File dir = new File(destDir, name); dir.mkdirs(); continue; } //log.debug("\tExtracting file "+name); File outFile = new File(destDir, name); if (!outFile.getParentFile().exists()) { //log.warn("weird zip: had to create parent: "+outFile.getParentFile()); outFile.getParentFile().mkdirs(); } try (FileOutputStream fos = new FileOutputStream(outFile); InputStream is = zf.getInputStream(e)) { int len; while ((len = is.read(b)) != -1) { fos.write(b, 0, len); } } } } }
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; }//w ww . java 2 s.c om 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:edu.ur.ir.ir_import.service.DefaultCollectionImportService.java
/** * Import the collections in the zip file. * /* w w w . j a va2s. c o m*/ * @see edu.ur.ir.ir_import.CollectionImportService#importCollections(java.io.File) */ public void importCollections(File zipFile, Repository repository) { if (log.isDebugEnabled()) { log.debug("import collections"); } try { ZipFile zip = new ZipFile(zipFile); ZipArchiveEntry entry = zip.getEntry("collection.xml"); File f = new File("collection.xml"); zipHelper.getZipEntry(f, entry, zip); if (f != null) { try { getCollections(f, repository, zip); } catch (DuplicateNameException e) { log.error(e); } FileUtils.deleteQuietly(f); } } catch (IOException e) { log.error(e); } }
From source file:at.spardat.xma.xdelta.JarDelta.java
/** * Main method to make {@link #computeDelta(String, String, ZipFile, ZipFile, ZipArchiveOutputStream)} available at * the command line.<br>// w w w . j ava2s .c o m * usage JarDelta source target output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { if (args.length != 3) { System.err.println("usage JarDelta source target output"); return; } try (ZipArchiveOutputStream output = new ZipArchiveOutputStream(new FileOutputStream(args[2]))) { new JarDelta().computeDelta(args[0], args[1], new ZipFile(args[0]), new ZipFile(args[1]), output); } }
From source file:com.android.repository.util.InstallerUtil.java
/** * Unzips the given zipped input stream into the given directory. * * @param in The (zipped) input stream. * @param out The directory into which to expand the files. Must exist. * @param fop The {@link FileOp} to use for file operations. * @param expectedSize Compressed size of the stream. * @param progress Currently only used for logging. * @throws IOException If we're unable to read or write. *//* ww w . j a va 2 s. c o m*/ public static void unzip(@NonNull File in, @NonNull File out, @NonNull FileOp fop, long expectedSize, @NonNull ProgressIndicator progress) throws IOException { if (!fop.exists(out) || !fop.isDirectory(out)) { throw new IllegalArgumentException("out must exist and be a directory."); } // ZipFile requires an actual (not mock) file, so make sure we have a real one. in = fop.ensureRealFile(in); progress.setText("Unzipping..."); ZipFile zipFile = new ZipFile(in); try { Enumeration entries = zipFile.getEntries(); progress.setFraction(0); while (entries.hasMoreElements()) { ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement(); String name = entry.getName(); File entryFile = new File(out, name); progress.setSecondaryText(name); if (entry.isUnixSymlink()) { ByteArrayOutputStream targetByteStream = new ByteArrayOutputStream(); readZipEntry(zipFile, entry, targetByteStream, expectedSize, progress); Path linkPath = fop.toPath(entryFile); Path linkTarget = fop.toPath(new File(targetByteStream.toString())); Files.createSymbolicLink(linkPath, linkTarget); } else if (entry.isDirectory()) { if (!fop.exists(entryFile)) { if (!fop.mkdirs(entryFile)) { progress.logWarning("failed to mkdirs " + entryFile); } } } else { if (!fop.exists(entryFile)) { File parent = entryFile.getParentFile(); if (parent != null && !fop.exists(parent)) { fop.mkdirs(parent); } if (!fop.createNewFile(entryFile)) { throw new IOException("Failed to create file " + entryFile); } } OutputStream unzippedOutput = fop.newFileOutputStream(entryFile); if (readZipEntry(zipFile, entry, unzippedOutput, expectedSize, progress)) { return; } if (!fop.isWindows()) { // get the mode and test if it contains the executable bit int mode = entry.getUnixMode(); //noinspection OctalInteger if ((mode & 0111) != 0) { try { fop.setExecutablePermission(entryFile); } catch (IOException ignore) { } } } } } } finally { ZipFile.closeQuietly(zipFile); } }