protected void load(String filename) { Logger.getLogger(getClass()).debug("Starting group in file " + filename); ZipFile zipfile = null; try { zipfile = new ZipFile(filename); fireBeginGroup(filename, zipfile.size()); Logger.getLogger(getClass()).debug("Loading ZipFile " + filename); load(zipfile); Logger.getLogger(getClass()).debug("Loaded ZipFile " + filename); fireEndGroup(filename); } catch (IOException ex) { Logger.getLogger(getClass()).error("Cannot load Zip file \"" + filename + "\"", ex); } finally { if (zipfile != null) { try { zipfile.close(); } catch (IOException ex) { // Ignore } } } }
private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name) throws IOException, FileNotFoundException { if (fileEntry == null) fileEntry = zip.getEntry(name); if (fileEntry == null) throw new FileNotFoundException("Can't find " + name + " in " + zip.getName()); File outFile = new File(sGREDir, name); if (outFile.lastModified() == fileEntry.getTime() && outFile.length() == fileEntry.getSize()) return false; File dir = outFile.getParentFile(); if (!dir.exists()) dir.mkdirs(); InputStream fileStream; fileStream = zip.getInputStream(fileEntry); OutputStream outStream = new FileOutputStream(outFile); while (fileStream.available() > 0) { int read = fileStream.read(buf, 0, buf.length); outStream.write(buf, 0, read); } fileStream.close(); outStream.close(); outFile.setLastModified(fileEntry.getTime()); return true; }
protected void unpackComponents() throws IOException, FileNotFoundException { File applicationPackage = new File(getApplication().getPackageResourcePath()); File componentsDir = new File(sGREDir, "components"); if (componentsDir.lastModified() == applicationPackage.lastModified()) return; componentsDir.mkdir(); componentsDir.setLastModified(applicationPackage.lastModified()); GeckoAppShell.killAnyZombies(); ZipFile zip = new ZipFile(applicationPackage); byte[] buf = new byte[32768]; try { if (unpackFile(zip, buf, null, "removed-files")) removeFiles(); } catch (Exception ex) { // This file may not be there, so just log any errors and move on Log.w(LOG_FILE_NAME, "error removing files", ex); } // copy any .xpi file into an extensions/ directory Enumeration<? extends ZipEntry> zipEntries = zip.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = zipEntries.nextElement(); if (entry.getName().startsWith("extensions/") && entry.getName().endsWith(".xpi")) { Log.i("GeckoAppJava", "installing extension : " + entry.getName()); unpackFile(zip, buf, entry, entry.getName()); } } }
/** * @param garFile GAR file. * @param hasDescr Whether GAR file has descriptor. * @throws IOException If GAR file is not found. * @return Whether GAR file structure is correct. */ private boolean checkStructure(File garFile, boolean hasDescr) throws IOException { ZipFile zip = new ZipFile(garFile); String descr = "META-INF/ignite.xml"; ZipEntry entry = zip.getEntry(descr); if (entry == null && !hasDescr) { if (log().isInfoEnabled()) { log() .info( "Process deployment without descriptor file [path=" + descr + ", file=" + garFile.getAbsolutePath() + ']'); } return true; } else if (entry != null && hasDescr) { InputStream in = null; try { in = new BufferedInputStream(zip.getInputStream(entry)); return true; } finally { U.close(in, log()); } } else return false; }
public static void main(final String[] args) throws IOException { File f = new File("pokus.zip"); // ZipFile zf = new ZipFile(f, ZipFile.OPEN_READ); // ZipFile zf = new ZipFile(f, ZipFile.OPEN_READ | ZipFile.OPEN_DELETE); ZipFile zf = new ZipFile(f, ZipFile.OPEN_DELETE); System.out.println("pocet zapakovanych polozek: " + zf.size()); }
/** * Checks the contents of the specified zip entry. * * @param file file to be checked * @param data expected file contents * @throws IOException I/O exception */ private static void checkEntry(final String file, final byte[] data) throws IOException { ZipFile zf = null; try { zf = new ZipFile(TMPZIP); final ZipEntry ze = zf.getEntry(file); assertNotNull("File not found: " + file, ze); final DataInputStream is = new DataInputStream(zf.getInputStream(ze)); final byte[] dt = new byte[(int) ze.getSize()]; is.readFully(dt); assertTrue( "Wrong contents in file \"" + file + "\":" + Prop.NL + "Expected: " + string(data) + Prop.NL + "Found: " + string(dt), eq(data, dt)); } finally { if (zf != null) zf.close(); } }
private void deflate(String tmpDir, String path) { String tmpFile = "tmp-" + Utils.timestamp() + ".zip"; try { ZipFile zipFile = new ZipFile(tmpFile); ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); parameters.setIncludeRootFolder(false); zipFile.addFolder(tmpDir, parameters); } catch (Exception e) { e.printStackTrace(); return; } File from = null; File to = null; try { File target = new File(path); if (target.exists()) FileUtils.forceDelete(target); from = new File(tmpFile); to = new File(path); FileUtils.moveFile(from, to); } catch (IOException e) { Utils.onError(new Error.FileMove(tmpFile, path)); } try { FileUtils.deleteDirectory(new File(tmpDir)); } catch (IOException e) { Utils.log("can't delete temporary folder"); } }
protected void load(ZipFile zipfile) throws IOException { Enumeration entries = zipfile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); fireBeginFile(entry.getName()); Logger.getLogger(getClass()) .debug("Starting file " + entry.getName() + " (" + entry.getSize() + " bytes)"); byte[] bytes = null; InputStream in = null; try { in = zipfile.getInputStream(entry); bytes = readBytes(in); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { // Ignore } } } Logger.getLogger(getClass()) .debug("Passing up file " + entry.getName() + " (" + bytes.length + " bytes)"); getLoader().load(entry.getName(), new ByteArrayInputStream(bytes)); fireEndFile(entry.getName()); } }
/** Lists contents of JAR file, via ZipFile. */ void list(String fname, String files[]) throws IOException { ZipFile zf = new ZipFile(fname); Enumeration<? extends ZipEntry> zes = zf.entries(); while (zes.hasMoreElements()) { printEntry(zes.nextElement(), files); } zf.close(); }
public static void main(String[] args) throws Exception { Reader trainingFile = null; // Process arguments int restArgs = commandOptions.processOptions(args); // Check arguments if (restArgs != args.length) { commandOptions.printUsage(true); throw new IllegalArgumentException("Unexpected arg " + args[restArgs]); } if (trainFileOption.value == null) { commandOptions.printUsage(true); throw new IllegalArgumentException("Expected --train-file FILE"); } if (modelFileOption.value == null) { commandOptions.printUsage(true); throw new IllegalArgumentException("Expected --model-file FILE"); } // Get the CRF structure specification. ZipFile zipFile = new ZipFile(modelFileOption.value); ZipEntry zipEntry = zipFile.getEntry("crf-info.xml"); CRFInfo crfInfo = new CRFInfo(zipFile.getInputStream(zipEntry)); StringBuffer crfInfoBuffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry))); String line; while ((line = reader.readLine()) != null) { crfInfoBuffer.append(line).append('\n'); } reader.close(); // Create the CRF, and train it. CRF4 crf = createCRF(trainFileOption.value, crfInfo); // Create a new zip file for our output. This will overwrite // the file we used for input. ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFileOption.value)); // Copy the CRF info xml to the output zip file. zos.putNextEntry(new ZipEntry("crf-info.xml")); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zos)); writer.write(crfInfoBuffer.toString()); writer.flush(); zos.closeEntry(); // Save the CRF classifier model to the output zip file. zos.putNextEntry(new ZipEntry("crf-model.ser")); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(crf); oos.flush(); zos.closeEntry(); zos.close(); }
public void installFramework(File frameFile, String tag) throws AndrolibException { InputStream in = null; ZipOutputStream out = null; try { ZipFile zip = new ZipFile(frameFile); ZipEntry entry = zip.getEntry("resources.arsc"); if (entry == null) { throw new AndrolibException("Can't find resources.arsc file"); } in = zip.getInputStream(entry); byte[] data = IOUtils.toByteArray(in); ARSCData arsc = ARSCDecoder.decode(new ByteArrayInputStream(data), true, true); publicizeResources(data, arsc.getFlagsOffsets()); File outFile = new File( getFrameworkDir(), String.valueOf(arsc.getOnePackage().getId()) + (tag == null ? "" : '-' + tag) + ".apk"); out = new ZipOutputStream(new FileOutputStream(outFile)); out.setMethod(ZipOutputStream.STORED); CRC32 crc = new CRC32(); crc.update(data); entry = new ZipEntry("resources.arsc"); entry.setSize(data.length); entry.setCrc(crc.getValue()); out.putNextEntry(entry); out.write(data); LOGGER.info("Framework installed to: " + outFile); } catch (ZipException ex) { throw new AndrolibException(ex); } catch (IOException ex) { throw new AndrolibException(ex); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { } } if (out != null) { try { out.close(); } catch (IOException ex) { } } } }
public static void main(String[] args) { try { ZipFile zipFile = new ZipFile(testDirName + zipFileName); ZipEntry ze = zipFile.getEntry(zipEntryName); byte[] digest1 = getZipDigest(zipFile, ze, true); System.out.println("Digest1: " + Base64Util.encode(digest1)); byte[] digest2 = getZipDigest(zipFile, ze, false); System.out.println("Digest2: " + Base64Util.encode(digest2)); } catch (Exception ex) { System.out.println("Error: " + ex.toString()); ex.printStackTrace(System.out); } }
// Take a tree of files starting in a directory in a zip file // and copy them to a disk directory, recreating the tree. private int unpackZipFile( File inZipFile, String directory, String parent, boolean suppressFirstPathElement) { int count = 0; if (!inZipFile.exists()) return count; parent = parent.trim(); if (!parent.endsWith(File.separator)) parent += File.separator; if (!directory.endsWith(File.separator)) directory += File.separator; File outFile = null; try { ZipFile zipFile = new ZipFile(inZipFile); Enumeration zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipEntries.nextElement(); String name = entry.getName().replace('/', File.separatorChar); if (name.startsWith(directory)) { if (suppressFirstPathElement) name = name.substring(directory.length()); outFile = new File(parent + name); // Create the directory, just in case if (name.indexOf(File.separatorChar) >= 0) { String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1); File dirFile = new File(parent + p); dirFile.mkdirs(); } if (!entry.isDirectory()) { System.out.println("Installing " + outFile); // Copy the file BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile)); BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry)); int size = 1024; int n = 0; byte[] b = new byte[size]; while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n); in.close(); out.flush(); out.close(); // Count the file count++; } } } zipFile.close(); } catch (Exception e) { System.err.println("...an error occured while installing " + outFile); e.printStackTrace(); System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage()); return -count; } System.out.println(count + " files were installed."); return count; }
public static void main(String[] args) throws Exception { int iterations = 0; File zFile1 = new File(System.getProperty("test.src", "."), "pkware123456789012345.zip"); while (iterations < 2500) { ZipFile zipFile = new ZipFile(zFile1); List entries = Collections.list(zipFile.entries()); for (Iterator it = entries.iterator(); it.hasNext(); ) { ZipEntry zipEntry = (ZipEntry) it.next(); InputStream in = zipFile.getInputStream(zipEntry); in.close(); } iterations++; } }
static List<ZLFile> archiveEntries(ZLFile archive) { try { final ZipFile zf = ZLZipEntryFile.getZipFile(archive); final Collection<LocalFileHeader> headers = zf.headers(); if (!headers.isEmpty()) { ArrayList<ZLFile> entries = new ArrayList<ZLFile>(headers.size()); for (LocalFileHeader h : headers) { entries.add(new ZLZipEntryFile(archive, h.FileName)); } return entries; } } catch (IOException e) { } return Collections.emptyList(); }
/** * Get an input stream for a resource contained in the jar file * * @param name file name of the resource within the jar file * @return an input stream representing the resouce if it exists or null */ public InputStream getResourceAsStream(String name) { if (zfile == null || hasChanged()) { update(); } try { if (zfile == null) return null; ZipEntry e = zfile.getEntry(name); if (e != null) return zfile.getInputStream(e); } catch (Exception e) { if (verbose) System.err.println("RJavaClassLoader$UnixJarFile: exception: " + e.getMessage()); } return null; }
private String inflate(String path) { if (!new File(path).canRead()) { Utils.onError(new Error.FileRead(path)); return null; } String tmpDir = "tmp-" + Utils.timestamp(); try { ZipFile zipFile = new ZipFile(path); zipFile.extractAll(tmpDir); } catch (Exception e) { e.printStackTrace(); return null; } return tmpDir; }
public static String[] getZipList(String zipFile) throws ZipException, IOException { File file = new File(zipFile); ZipFile zip = new ZipFile(file); Enumeration<? extends ZipEntry> zipFileEntries = zip.entries(); ArrayList<String> files = new ArrayList<String>(); // Process each entry while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); files.add(currentEntry); } return files.toArray(new String[files.size()]); }
public static void closeQuietly(final ZipFile zipfile) { if (zipfile != null) { try { zipfile.close(); } catch (IOException ex) { } } }
public static void extract(String zipFile, String newPath, boolean overwrite) throws ZipException, IOException { File file = new File(zipFile); ZipFile zip = new ZipFile(file); new File(newPath).mkdir(); Enumeration<? extends ZipEntry> zipFileEntries = zip.entries(); // Process each entry while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, currentEntry); // destFile = new File(newPath, destFile.getName()); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); if (!entry.isDirectory()) { if (!overwrite && destFile.exists()) continue; BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } close(dest); close(is); } } }
/* @Override */ public void update() { try { if (zfile != null) { zfile.close(); } zfile = new ZipFile(this); } catch (Exception tryCloseX) { } /* time stamp */ super.update(); }
protected void loadAirspacesFromPath(String path, Collection<Airspace> airspaces) { File file = ExampleUtil.saveResourceToTempFile(path, ".zip"); if (file == null) return; try { ZipFile zipFile = new ZipFile(file); ZipEntry entry = null; for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements(); entry = e.nextElement()) { if (entry == null) continue; String name = WWIO.getFilename(entry.getName()); if (!(name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml"))) continue; String[] tokens = name.split("-"); try { Class c = Class.forName(tokens[0]); Airspace airspace = (Airspace) c.newInstance(); BufferedReader input = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry))); String s = input.readLine(); airspace.restoreState(s); airspaces.add(airspace); if (tokens.length >= 2) { airspace.setValue(AVKey.DISPLAY_NAME, tokens[1]); } } catch (Exception ex) { ex.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } }
/** Extracts specified entries from JAR file, via ZipFile. */ void extract(String fname, String files[]) throws IOException { ZipFile zf = new ZipFile(fname); Set<ZipEntry> dirs = newDirSet(); Enumeration<? extends ZipEntry> zes = zf.entries(); while (zes.hasMoreElements()) { ZipEntry e = zes.nextElement(); InputStream is; if (files == null) { dirs.add(extractFile(zf.getInputStream(e), e)); } else { String name = e.getName(); for (String file : files) { if (name.startsWith(file)) { dirs.add(extractFile(zf.getInputStream(e), e)); break; } } } } zf.close(); updateLastModifiedTime(dirs); }
/** * Unzips the transferred file. Returns <code>true</code> if the unzip was successful, and <code> * false</code> otherwise. In case of failure, this method handles setting an appropriate * response. */ private boolean completeUnzip(HttpServletRequest req, HttpServletResponse resp) throws ServletException { IPath destPath = new Path(getPath()); try { ZipFile source = new ZipFile(new File(getStorageDirectory(), FILE_DATA)); IFileStore destinationRoot = NewFileServlet.getFileStore(destPath); Enumeration<? extends ZipEntry> entries = source.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); IFileStore destination = destinationRoot.getChild(entry.getName()); if (entry.isDirectory()) destination.mkdir(EFS.NONE, null); else { destination.getParent().mkdir(EFS.NONE, null); IOUtilities.pipe( source.getInputStream(entry), destination.openOutputStream(EFS.NONE, null), false, true); } } source.close(); } catch (ZipException e) { // zip exception implies client sent us invalid input String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString()); statusHandler.handleRequest( req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e)); return false; } catch (Exception e) { // other failures should be considered server errors String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString()); statusHandler.handleRequest( req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); return false; } return true; }
public static String ExtractZip(String zipName, String outFolder) { try { File sourceZipFile = new File(zipName); File outDirectory = new File(outFolder); ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); Enumeration zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); for (int X = currentEntry.length() - 1; X >= 0; X--) { if (currentEntry.charAt(X) == '\\' || currentEntry.charAt(X) == '/') { currentEntry = currentEntry.substring(X + 1); break; } } File destFile = new File(outDirectory, currentEntry); if (destFile.getParentFile() != null) destFile.getParentFile().mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((currentByte = is.read(data, 0, BUFFER)) != -1) dest.write(data, 0, currentByte); dest.flush(); dest.close(); is.close(); } } zipFile.close(); return "success"; } catch (IOException e) { return "Failed to extract zip: " + e.toString(); } }
private static byte[] getZipDigest(ZipFile zipFile, ZipEntry ze, boolean zip) throws ZipException, IOException, Exception { System.out.println("z2e: " + ze.toString()); InputStream is = null; if (zip) is = zipFile.getInputStream(ze); else is = new FileInputStream(testDirName + ze.toString()); MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] buf = new byte[1024]; int count; while ((count = is.read(buf)) != -1) { System.out.println("Count: " + count); sha.update(buf, 0, count); } is.close(); return sha.digest(); }
public URL getResource(String name) { if (zfile == null || zfile.getEntry(name) == null) { return null; } URL u = null; if (urlPrefix == null) { try { urlPrefix = "jar:" + toURL().toString() + "!"; } catch (java.net.MalformedURLException ex) { } catch (java.io.IOException ex) { } } try { u = new URL(urlPrefix + name); } catch (java.net.MalformedURLException ex) { /* not to worry */ } return u; }
public void close() throws IOException { zf.close(); }
public Enumeration entries() { return zf.entries(); }
public int size() { return zf.size(); }