List of usage examples for java.util.zip ZipFile close
public void close() throws IOException
From source file:org.openstreetmap.josm.tools.ImageProvider.java
private static ImageResource getIfAvailableZip(String full_name, File archive, ImageType type) { ZipFile zipFile = null; try {//from ww w .j a va 2 s . c o m zipFile = new ZipFile(archive); ZipEntry entry = zipFile.getEntry(full_name); if (entry != null) { int size = (int) entry.getSize(); int offs = 0; byte[] buf = new byte[size]; InputStream is = null; try { is = zipFile.getInputStream(entry); switch (type) { case SVG: URI uri = getSvgUniverse().loadSVG(is, full_name); SVGDiagram svg = getSvgUniverse().getDiagram(uri); return svg == null ? null : new ImageResource(svg); case OTHER: while (size > 0) { int l = is.read(buf, offs, size); offs += l; size -= l; } BufferedImage img = null; try { img = ImageIO.read(new ByteArrayInputStream(buf)); } catch (IOException e) { } return img == null ? null : new ImageResource(img); default: throw new AssertionError(); } } finally { if (is != null) { is.close(); } } } } catch (Exception e) { System.err.println(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString())); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException ex) { } } } return null; }
From source file:parser.axml.ManifestParser.java
/** * ? AndroidManifest.xml <code>ManifestInfo </code>. * * @param pFile apk //from ww w . j a v a 2s . c o m * @return ??????? null */ public ManifestInfo parse(File pFile) throws IOException { ManifestInfo manifestInfo = new ManifestInfo(); m_noback = false; ZipFile zipFile; InputStream aXMLInputStream = null; InputStream arscInputStream = null; try { zipFile = new ZipFile(pFile); ZipEntry zipEntry = zipFile.getEntry("AndroidManifest.xml"); if (zipEntry != null) { aXMLInputStream = zipFile.getInputStream(zipEntry); } else { manifestInfo = null; } zipEntry = zipFile.getEntry("resources.arsc"); if (zipEntry != null) { arscInputStream = zipFile.getInputStream(zipEntry); } if (arscInputStream != null) { m_arsc = IOUtils.toByteArray(arscInputStream); } } catch (IOException e) { throw new IOException(e.getMessage()); } if (aXMLInputStream != null) { try { parseManifest(aXMLInputStream, manifestInfo); manifestInfo.back = !m_noback; manifestInfo.xml = (m_xml == null) ? null : m_xml.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } try { zipFile.close(); } catch (IOException e) { e.printStackTrace(); } if (aXMLInputStream != null) { try { aXMLInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (arscInputStream != null) { try { arscInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return manifestInfo; }
From source file:com.alibaba.jstorm.yarn.utils.JStormUtils.java
/** * Extra dir from the jar to destdir/*from w w w .jav a 2 s . c o m*/ * * @param jarpath * @param dir * @param destdir */ public static void extractDirFromJar(String jarpath, String dir, String destdir) { ZipFile zipFile = null; try { zipFile = new ZipFile(jarpath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries != null && entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); if (!ze.isDirectory() && ze.getName().startsWith(dir)) { InputStream in = zipFile.getInputStream(ze); try { File file = new File(destdir, ze.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { if (in != null) in.close(); } } } } catch (Exception e) { LOG.warn("No " + dir + " from " + jarpath + "!\n" + e.getMessage()); } finally { if (zipFile != null) try { zipFile.close(); } catch (Exception e) { LOG.warn(e.getMessage()); } } }
From source file:org.structr.core.module.ModuleService.java
private Module loadResource(String resource) throws IOException { // create module DefaultModule ret = new DefaultModule(resource); Set<String> classes = ret.getClasses(); if (resource.endsWith(".jar") || resource.endsWith(".war")) { ZipFile zipFile = new ZipFile(new File(resource), ZipFile.OPEN_READ); // conventions that might be useful here: // ignore entries beginning with meta-inf/ // handle entries beginning with images/ as IMAGE // handle entries beginning with pages/ as PAGES // handle entries ending with .jar as libraries, to be deployed to WEB-INF/lib // handle other entries as potential page and/or entity classes // .. to be extended // (entries that end with "/" are directories) for (Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements();) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName.endsWith(".class")) { String fileEntry = entry.getName().replaceAll("[/]+", "."); // add class entry to Module classes.add(fileEntry.substring(0, fileEntry.length() - 6)); }//from w ww .j a v a 2s. com } zipFile.close(); } else if (resource.endsWith(classesDir)) { addClassesRecursively(new File(resource), classesDir, classes); } else if (resource.endsWith(testClassesDir)) { addClassesRecursively(new File(resource), testClassesDir, classes); } return ret; }
From source file:abfab3d.io.input.STSReader.java
/** * Load a STS file into a grid.// w ww .ja v a 2s . c om * * @param file The zip file * @return * @throws java.io.IOException */ public TriangleMesh[] loadMeshes(String file) throws IOException { ZipFile zip = null; TriangleMesh[] ret_val = null; try { zip = new ZipFile(file); ZipEntry entry = zip.getEntry("manifest.xml"); if (entry == null) { throw new IOException("Cannot find manifest.xml in top level"); } InputStream is = zip.getInputStream(entry); mf = parseManifest(is); if (mf == null) { throw new IOException("Could not parse manifest file"); } List<STSPart> plist = mf.getParts(); int len = plist.size(); ret_val = new TriangleMesh[len]; for (int i = 0; i < len; i++) { STSPart part = plist.get(i); ZipEntry ze = zip.getEntry(part.getFile()); MeshReader reader = new MeshReader(zip.getInputStream(ze), "", FilenameUtils.getExtension(part.getFile())); IndexedTriangleSetBuilder its = new IndexedTriangleSetBuilder(); reader.getTriangles(its); // TODO: in this case we could return a less heavy triangle mesh struct? WingedEdgeTriangleMesh mesh = new WingedEdgeTriangleMesh(its.getVertices(), its.getFaces()); ret_val[i] = mesh; } return ret_val; } finally { if (zip != null) zip.close(); } }
From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java
private File appendPomPropertiesToJar(final String pomProperties, final String jarPath, final GAV gav) { File originalJarFile = new File(jarPath); File appendedJarFile = new File(jarPath + ".tmp"); try {//from w w w .j a v a 2 s . com ZipFile war = new ZipFile(originalJarFile); ZipOutputStream append = new ZipOutputStream(new FileOutputStream(appendedJarFile)); // first, copy contents from existing war Enumeration<? extends ZipEntry> entries = war.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); append.putNextEntry(e); if (!e.isDirectory()) { IOUtil.copy(war.getInputStream(e), append); } append.closeEntry(); } // append pom.properties ZipEntry e = new ZipEntry(getPomPropertiesPath(gav)); append.putNextEntry(e); append.write(pomProperties.getBytes()); append.closeEntry(); // close war.close(); append.close(); } catch (ZipException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } //originalJarFile.delete(); //appendedJarFile.renameTo(originalJarFile); return appendedJarFile; }
From source file:org.docx4j.openpackaging.io.LoadFromZipNG.java
public OpcPackage get(File f) throws Docx4JException { log.info("Filepath = " + f.getPath()); ZipFile zf = null; try {// w w w .j a v a 2 s .c o m if (!f.exists()) { log.info("Couldn't find " + f.getPath()); } zf = new ZipFile(f); } catch (IOException ioe) { ioe.printStackTrace(); throw new Docx4JException("Couldn't get ZipFile", ioe); } HashMap<String, ByteArray> partByteArrays = new HashMap<String, ByteArray>(); Enumeration entries = zf.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); log.info("\n\n" + entry.getName() + "\n"); InputStream in = null; try { byte[] bytes = getBytesFromInputStream(zf.getInputStream(entry)); partByteArrays.put(entry.getName(), new ByteArray(bytes)); } catch (Exception e) { e.printStackTrace(); } } // At this point, we've finished with the zip file try { zf.close(); } catch (IOException exc) { exc.printStackTrace(); } return process(partByteArrays); }
From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java
private File removeDuplicatesFromJar(File in, List<String> duplicates) { String target = projectOutputDirectory.getAbsolutePath(); File tmp = new File(target, "unpacked-embedded-jars"); tmp.mkdirs();/*from ww w . j a v a 2s .co m*/ File out = new File(tmp, in.getName()); if (out.exists()) { return out; } else { try { out.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // Create a new Jar file final FileOutputStream fos; final ZipOutputStream jos; try { fos = new FileOutputStream(out); jos = new ZipOutputStream(fos); } catch (FileNotFoundException e1) { getLog().error( "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found"); return null; } final ZipFile inZip; try { inZip = new ZipFile(in); Enumeration<? extends ZipEntry> entries = inZip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // If the entry is not a duplicate, copy. if (!duplicates.contains(entry.getName())) { // copy the entry header to jos jos.putNextEntry(entry); InputStream currIn = inZip.getInputStream(entry); copyStreamWithoutClosing(currIn, jos); currIn.close(); jos.closeEntry(); } } } catch (IOException e) { getLog().error("Cannot removing duplicates : " + e.getMessage()); return null; } try { inZip.close(); jos.close(); fos.close(); } catch (IOException e) { // ignore it. } getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath()); return out; }
From source file:mobac.mapsources.loader.MapPackManager.java
/** * Calculate the md5sum on all files in the map pack file (except those in META-INF) and their filenames inclusive * path in the map pack file).//from w ww. jav a 2s .co m * * @param mapPackFile * @return * @throws IOException * @throws NoSuchAlgorithmException */ public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException { ZipFile zip = new ZipFile(mapPackFile); try { Enumeration<? extends ZipEntry> entries = zip.entries(); MessageDigest md5Total = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5"); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) continue; // Do not hash files from META-INF String name = entry.getName(); if (name.toUpperCase().startsWith("META-INF")) continue; md5.reset(); InputStream in = zip.getInputStream(entry); byte[] data = Utilities.getInputBytes(in); in.close(); // name = name.replaceAll("\\\\", "/"); byte[] digest = md5.digest(data); log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\""); md5Total.update(digest); md5Total.update(name.getBytes()); } String md5sum = Hex.encodeHexString(md5Total.digest()); log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum); return md5sum; } finally { zip.close(); } }
From source file:it.readbeyond.minstrel.librarian.FormatHandlerABZ.java
private List<ZipAsset> parseM3UPlaylistEntry(String path, String playlistEntry) { List<ZipAsset> assets = new ArrayList<ZipAsset>(); try {/*from ww w . j a v a 2s . c om*/ ZipFile zipFile = new ZipFile(new File(path), ZipFile.OPEN_READ); ZipEntry ze = zipFile.getEntry(playlistEntry); String text = this.getZipEntryText(zipFile, ze); String[] lines = text.split("\n"); // check that the first line starts with the M3U header if ((lines.length > 0) && (lines[0].startsWith(ABZ_M3U_HEADER))) { for (int i = 1; i < lines.length; i++) { String line = lines[i].trim(); // if line starts with the M3U preamble, parse it if (line.startsWith(ABZ_M3U_LINE_PREAMBLE)) { HashMap<String, String> meta = new HashMap<String, String>(); // get track duration and title Matcher m = ABZ_M3U_LINE_PATTERN.matcher(line); if (m.find()) { meta.put("duration", m.group(1)); meta.put("title", m.group(2)); } String line2 = lines[i + 1].trim(); // generate entry path File w = new File(new File(playlistEntry).getParent(), line2); line2 = w.getAbsolutePath().substring(1); // add asset assets.add(new ZipAsset(line2, meta)); // go to the next pair of lines i += 1; } } } // close ZIP zipFile.close(); } catch (Exception e) { // nothing } return assets; }