private static void addParts( final XMLSignatureFactory fac, final ContentTypeManager contentTypeManager, final List<Reference> references, final byte[] ooXmlDocument, final String[] applications, final DigestMethod digestMethod) throws IOException { final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(ooXmlDocument)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!startsWithAnyOfThose(zipEntry.getName(), applications)) { continue; } final String contentType = contentTypeManager.getContentType(zipEntry.getName()); // Solo se anade la referencia si existe contentType if (contentType != null) { final Reference reference = fac.newReference( "/" + zipEntry.getName() + "?ContentType=" + contentType, digestMethod); //$NON-NLS-1$ //$NON-NLS-2$ references.add(reference); } } }
/* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); reader = new ImageReader(); reader.setMetadataOptions(getMetadataOptions()); reader.setMetadataFiltered(isMetadataFiltered()); reader.setOriginalMetadataPopulated(isOriginalMetadataPopulated()); reader.setNormalized(isNormalized()); reader.setMetadataStore(getMetadataStore()); // NB: We need a raw handle on the ZIP data itself, not a ZipHandle. IRandomAccess rawHandle = Location.getHandle(id, false, false); in = new RandomAccessInputStream(rawHandle, id); ZipInputStream zip = new ZipInputStream(in); while (true) { ZipEntry ze = zip.getNextEntry(); if (ze == null) break; ZipHandle handle = new ZipHandle(id, ze); Location.mapFile(ze.getName(), handle); mappedFiles.add(ze.getName()); } ZipHandle base = new ZipHandle(id); reader.setId(base.getEntryName()); metadataStore = reader.getMetadataStore(); core = reader.getCoreMetadata(); metadata = reader.getGlobalMetadata(); base.close(); }
private void removePreviousModVersion(String modName, String installedVersion) { try { // Mod has been previously installed uninstall previous version File previousModZip = new File(cacheDir, modName + "-" + installedVersion + ".zip"); ZipFile zf = new ZipFile(previousModZip); Enumeration<? extends ZipEntry> entries = zf.entries(); // Go through zipfile of previous version and delete all file from // Modpack that exist in the zip while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } File file = new File(GameUpdater.modpackDir, entry.getName()); Util.log("Deleting '%s'", entry.getName()); if (file.exists()) { // File from mod exists.. delete it file.delete(); } } InstalledModsYML.removeMod(modName); } catch (IOException e) { e.printStackTrace(); } }
@Test public void shouldSetTimestampOfEntries() throws IOException { Calendar cal = Calendar.getInstance(); cal.set(1999, SEPTEMBER, 10); long old = getTimeRoundedToSeconds(cal.getTime()); long now = getTimeRoundedToSeconds(new Date()); try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output)) { ZipEntry oldAndValid = new ZipEntry("oldAndValid"); oldAndValid.setTime(old); out.putNextEntry(oldAndValid); ZipEntry current = new ZipEntry("current"); current.setTime(now); out.putNextEntry(current); } try (ZipInputStream in = new ZipInputStream(Files.newInputStream(output))) { ZipEntry entry = in.getNextEntry(); assertEquals("oldAndValid", entry.getName()); assertEquals(old, entry.getTime()); entry = in.getNextEntry(); assertEquals("current", entry.getName()); assertEquals(now, entry.getTime()); } }
/** * @return a mutable list * @throws IOException */ public static List<JSSourceFile> getDefaultExterns() throws IOException { InputStream input = CommandLineRunner.class.getResourceAsStream("/externs.zip"); ZipInputStream zip = new ZipInputStream(input); Map<String, JSSourceFile> externsMap = Maps.newHashMap(); for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) { LimitInputStream entryStream = new LimitInputStream(zip, entry.getSize()); externsMap.put( entry.getName(), JSSourceFile.fromInputStream( // Give the files an odd prefix, so that they do not conflict // with the user's files. "externs.zip//" + entry.getName(), entryStream)); } Preconditions.checkState( externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)), "Externs zip must match our hard-coded list of externs."); // Order matters, so the resources must be added to the result list // in the expected order. List<JSSourceFile> externs = Lists.newArrayList(); for (String key : DEFAULT_EXTERNS_NAMES) { externs.add(externsMap.get(key)); } return externs; }
private static void unZipFile(InputStream source, FileObject projectRoot) throws IOException { try { ZipInputStream str = new ZipInputStream(source); ZipEntry entry; while ((entry = str.getNextEntry()) != null) { if (entry.isDirectory()) { FileUtil.createFolder(projectRoot, entry.getName()); } else { FileObject fo = FileUtil.createData(projectRoot, entry.getName()); FileLock lock = fo.lock(); try { OutputStream out = fo.getOutputStream(lock); try { FileUtil.copy(str, out); } finally { out.close(); } } finally { lock.releaseLock(); } } } } finally { source.close(); } }
public static boolean unpackFileFromZip(Path zipfile, String filename, Path destDirectory) throws IOException { boolean ret = true; byte[] bytebuffer = new byte[BUFFERSIZE]; ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipfile.toFile())); ZipEntry zipentry; while ((zipentry = zipinputstream.getNextEntry()) != null) { if (zipentry.getName().equals(filename)) { Path newFile = destDirectory.resolve(zipentry.getName()); FileOutputStream fileoutputstream = new FileOutputStream(newFile.toFile()); int bytes; while ((bytes = zipinputstream.read(bytebuffer)) > -1) { fileoutputstream.write(bytebuffer, 0, bytes); } fileoutputstream.close(); zipinputstream.closeEntry(); zipinputstream.close(); return ret; } zipinputstream.closeEntry(); } zipinputstream.close(); return ret; }
public void unzip(File from, String to) throws FITTESTException { try { FileInputStream fis = new FileInputStream(from); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis, BUFFER)); ZipEntry entry = zis.getNextEntry(); while (entry != null) { int count; byte data[] = new byte[BUFFER]; File outFile = null; if (entry.isDirectory()) { outFile = new File(to, entry.getName()); outFile.mkdirs(); } else { outFile = new File(to, entry.getName()); FileOutputStream fos = new FileOutputStream(outFile); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { bos.write(data, 0, count); } bos.flush(); bos.close(); } zis.closeEntry(); entry = zis.getNextEntry(); } zis.close(); } catch (Exception e) { throw new FITTESTException(e.getMessage()); } }
/* shamelessly copied from PlugInManager */ private static Class toClass(ZipEntry entry, ClassLoader classLoader) { if (entry.isDirectory()) { return null; } if (!entry.getName().endsWith(".class")) { return null; } if (entry.getName().indexOf("$") != -1) { // I assume it's not necessary to load inner classes explicitly. // [Jon Aquino] return null; } String className = entry.getName(); className = className.substring(0, className.length() - ".class".length()); className = StringUtil.replaceAll(className, "/", "."); Class candidate; try { candidate = classLoader.loadClass(className); } catch (ClassNotFoundException e) { Assert.shouldNeverReachHere( "Class not found: " + className + ". Refine class name algorithm."); return null; } catch (Throwable t) { LOG.error("Throwable encountered loading " + className + ":"); // e.g. java.lang.VerifyError: class // org.apache.xml.serialize.XML11Serializer // overrides final method [Jon Aquino] t.printStackTrace(System.out); return null; } return candidate; }
private void unzip() throws IOException { int BUFFER = 2048; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile("update.zip"); Enumeration e = zipfile.entries(); (new File(root)).mkdir(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); output.setText(output.getText() + "\nExtracting: " + entry); if (entry.isDirectory()) { (new File(root + entry.getName())).mkdir(); } else { (new File(root + entry.getName())).createNewFile(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte[] data = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(root + entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); is.close(); } } }
/** * Helper for unzipping downloaded zips * * @param environment * @throws IOException */ private void unzip(Environment environment, ZipFile zipFile, File targetFile, String targetPath) throws IOException { String baseDirSuffix = null; try { Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); if (!zipEntries.hasMoreElements()) { logger.error("the zip archive has no entries"); } ZipEntry firstEntry = zipEntries.nextElement(); if (firstEntry.isDirectory()) { baseDirSuffix = firstEntry.getName(); } else { zipEntries = zipFile.entries(); } while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); if (zipEntry.isDirectory()) { continue; } String zipEntryName = zipEntry.getName(); zipEntryName = zipEntryName.replace('\\', '/'); if (baseDirSuffix != null && zipEntryName.startsWith(baseDirSuffix)) { zipEntryName = zipEntryName.substring(baseDirSuffix.length()); } File target = new File(targetFile, zipEntryName); FileSystemUtils.mkdirs(target.getParentFile()); Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target)); } } catch (IOException e) { logger.error( "failed to extract zip [" + zipFile.getName() + "]: " + ExceptionsHelper.detailedMessage(e)); return; } finally { try { zipFile.close(); } catch (IOException e) { // ignore } } File binFile = new File(targetFile, "bin"); if (binFile.exists() && binFile.isDirectory()) { File toLocation = new File(new File(environment.homeFile(), "bin"), targetPath); logger.info("found bin, moving to " + toLocation.getAbsolutePath()); FileSystemUtils.deleteRecursively(toLocation); binFile.renameTo(toLocation); } if (!new File(targetFile, "_site").exists()) { if (!FileSystemUtils.hasExtensions(targetFile, ".class", ".jar")) { logger.info("identified as a _site plugin, moving to _site structure ..."); File site = new File(targetFile, "_site"); File tmpLocation = new File(environment.pluginsFile(), targetPath + ".tmp"); targetFile.renameTo(tmpLocation); FileSystemUtils.mkdirs(targetFile); tmpLocation.renameTo(site); } } }
public static void unzip(InputStream is, File destDir) throws IOException { final int BUFFER = 2048; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); try { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { File dir = new File(destDir, entry.getName()); if (!dir.mkdir()) { throw new IOException("Failed to create directory " + dir); } } else { int count; byte contents[] = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(new File(destDir, entry.getName())); try { BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); try { while ((count = zis.read(contents, 0, BUFFER)) != -1) { dest.write(contents, 0, count); } } finally { dest.close(); } } finally { fos.close(); } } } } finally { zis.close(); } }
public static List<File> unzip(File zip, File toDir) throws IOException { ZipFile zf = null; List<File> files = null; try { zf = new ZipFile(zip); files = new ArrayList<File>(); Enumeration<?> entries = zf.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { new File(toDir, entry.getName()).mkdirs(); } else { InputStream input = null; OutputStream output = null; try { File f = new File(toDir, entry.getName()); input = zf.getInputStream(entry); output = new FileOutputStream(f); copy(input, output); files.add(f); } finally { closeQuietly(output); closeQuietly(input); } } } } finally { if (zf != null) { zf.close(); } } return files; }
public void parse( InputStream stream, ContentHandler baseHandler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { // As we don't know which of the metadata or the content // we'll hit first, catch the endDocument call initially EndDocumentShieldingContentHandler handler = new EndDocumentShieldingContentHandler(baseHandler); // Process the file in turn ZipInputStream zip = new ZipInputStream(stream); ZipEntry entry = zip.getNextEntry(); while (entry != null) { if (entry.getName().equals("mimetype")) { String type = IOUtils.toString(zip, "UTF-8"); metadata.set(Metadata.CONTENT_TYPE, type); } else if (entry.getName().equals("meta.xml")) { meta.parse(zip, new DefaultHandler(), metadata, context); } else if (entry.getName().endsWith("content.xml")) { content.parse(zip, handler, metadata, context); } entry = zip.getNextEntry(); } // Only now call the end document if (handler.getEndDocumentWasCalled()) { handler.reallyEndDocument(); } }
public static final boolean unzip(File file, File target) throws MojoExecutionException { Enumeration entries; ZipFile zipFile; display(" --- Extracting ---"); try { zipFile = new ZipFile(file); entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { display(" + " + entry.getName()); File newFolder = new File(target + "/" + entry.getName()); newFolder.mkdir(); continue; } display(" " + entry.getName()); copyInputStream( zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(target + "/" + entry.getName()))); } zipFile.close(); return true; } catch (IOException ioe) { throw new MojoExecutionException("Unzip Error", ioe); } }
/** * Unzip the zip file and put all the files in the zip file to the path. * * <p><strong>WARN:</strong> If the file list can not pass the checker's validation, delete all * the contents in the {@code path}, and the {@code path} itself. * * @param zipFile zipFile object * @param path target path * @param checker checker to validate ZIP files. * @throws AppException if exception occurred, convert them into {@code AppException} object. */ public static void unzipFile(ZipFile zipFile, String path, Checker<File> checker) throws AppException { try { Enumeration<?> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) enumeration.nextElement(); if (zipEntry.isDirectory()) { if (!new File(path + "/" + zipEntry.getName()).mkdirs()) throw new Exception(); continue; } File file = new File(path + "/" + zipEntry.getName()); File parent = file.getParentFile(); if (parent != null && !parent.exists()) { if (!parent.mkdirs()) throw new AppException(); } FileUtil.saveToFile(zipFile.getInputStream(zipEntry), new FileOutputStream(file)); } zipFile.close(); File targetFile = new File(path); try { checker.check(targetFile); } catch (AppException e) { FileUtil.clearDirectory(targetFile.getAbsolutePath()); throw e; } } catch (AppException e) { throw e; } catch (Exception e) { e.printStackTrace(); throw new AppException("Unzip zip file error."); } }
private List<ComponentDeclaration> getDeclaredComponents(File jarFile) throws IOException { ZipInputStream zis = new ZipInputStream(new FileInputStream(jarFile)); List<ComponentDeclaration> componentDeclarations = null; List<ComponentDeclaration> componentOverrideDeclarations = null; try { for (ZipEntry entry = zis.getNextEntry(); entry != null && (componentDeclarations == null || componentOverrideDeclarations == null); entry = zis.getNextEntry()) { if (entry.getName().equals(ComponentAnnotationLoader.COMPONENT_LIST)) { componentDeclarations = this.jarLoader.getDeclaredComponents(zis); } else if (entry.getName().equals(ComponentAnnotationLoader.COMPONENT_OVERRIDE_LIST)) { componentOverrideDeclarations = this.jarLoader.getDeclaredComponents(zis); } } } finally { zis.close(); } // Merge all overrides found with a priority of 0. This is purely for backward compatibility // since the // override files is now deprecated. if (componentOverrideDeclarations != null) { if (componentDeclarations == null) { componentDeclarations = new ArrayList<ComponentDeclaration>(); } for (ComponentDeclaration componentOverrideDeclaration : componentOverrideDeclarations) { componentDeclarations.add( new ComponentDeclaration(componentOverrideDeclaration.getImplementationClassName(), 0)); } } return componentDeclarations; }
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()); } }
/** * Unzip an archive * * @param zipname the archive name, stored in the temp directory * @return boolean state indicating the unzip success */ private boolean UnzipLangArchive(String zipname) { ZipFile zipFile; // reset the statuses, thus we will be able to get the progress[%] status m_lMaxDownloadSz = GetZipSize(zipname); m_lCurrentDownloadSz = 0; try { zipFile = new ZipFile(zipname); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); String filename = entry.getName(); Log.v(TAG, "Extracting file: " + filename); if (!CopyInputStream(zipFile.getInputStream(entry), entry.getSize(), entry.getName())) return false; m_ParentProgressDialog.setProgress(GetDownloadStatus()); } zipFile.close(); } catch (IOException ioe) { Log.v(TAG, "exception:" + ioe.toString()); return false; } return true; }
private List<String> getClasses() throws IOException { if (zipClasses.size() != 0) { return zipClasses; } List<String> classNames = new ArrayList<String>(); ZipInputStream zip = null; try { zip = new ZipInputStream(new FileInputStream("plugins/DDCustomPlugin.jar")); } catch (FileNotFoundException e) { throw new IOException(); } for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) if (entry.getName().endsWith(".class") && !entry.isDirectory()) { // This ZipEntry represents a class. Now, what class does it represent? StringBuilder className = new StringBuilder(); for (String part : entry.getName().split("/")) { if (className.length() != 0) className.append("."); className.append(part); if (part.endsWith(".class")) className.setLength(className.length() - ".class".length()); } if (className.toString().indexOf("$") == -1) classNames.add(className.toString()); } zipClasses = classNames; return classNames; }
/** * extracts class files from jar/zip archive to specified path. See <code>IDecompiler</code> * documentation for the format of pareameters. */ public static void extract( String archivePath, String packege, String className, boolean inner, String to) throws IOException { ZipFile archive = new ZipFile(archivePath); List entries = findRelevant(archive, packege, className, inner); InputStream in = null; OutputStream out = null; byte[] buffer = new byte[2048]; ZipEntry entry; String outFile; int lastSep, amountRead; for (int i = 0; i < entries.size(); i++) { entry = (ZipEntry) entries.get(i); outFile = entry.getName(); if ((lastSep = outFile.lastIndexOf('/')) != -1) outFile = outFile.substring(lastSep); try { in = archive.getInputStream(entry); if (in == null) throw new IOException("Zip file entry <" + entry.getName() + "> not found"); out = new FileOutputStream(to + File.separator + outFile); while ((amountRead = in.read(buffer)) != -1) out.write(buffer, 0, amountRead); } finally { if (in != null) in.close(); if (out != null) out.close(); } } }
/** * 真正的解压方法 会删除解压完的所有Zip文档 * * @param File 一个。zip的 文件 */ public static void myzijide(File file) throws IOException { ZipInputStream zip = new ZipInputStream(new FileInputStream(file)); ZipEntry en = null; BufferedOutputStream out = null; // 循环读取ZIP文件中的内容 while ((en = zip.getNextEntry()) != null) { if (en.isDirectory()) { File f = new File(file.getParent() + "\\" + en.getName()); if (!f.exists()) f.mkdirs(); continue; } // 发现好多文件夹存在 Thumbs , 定一个识别将他过滤 // 文件名中含有Thumbs 将 不 解压 if (en.getName().contains("Thumbs")) { continue; } // 实际的输出方法 out = new BufferedOutputStream(new FileOutputStream(file.getParent() + "\\" + en.getName())); int i = -1; byte[] b = new byte[1024]; while ((i = zip.read(b)) != -1) { out.write(b, 0, i); } out.close(); } zip.close(); // 删除文件 String tishi = file.delete() ? "yes" : "no"; System.out.println(file.getName() + "解压完成并删除 ?" + tishi); }
public static LinkedHashMap readJarFileEntries(File jarFile) throws Exception { LinkedHashMap entries = new LinkedHashMap(); JarFile jarFileWrapper = null; if (jarFile != null) { logger.debug("Reading jar entries from " + jarFile.getAbsolutePath()); try { jarFileWrapper = new JarFile(jarFile); Enumeration iter = jarFileWrapper.entries(); while (iter.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) iter.nextElement(); InputStream entryStream = jarFileWrapper.getInputStream(zipEntry); ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(); try { IOUtils.copy(entryStream, byteArrayStream); entries.put(zipEntry.getName(), byteArrayStream.toByteArray()); logger.debug( "Read jar entry " + zipEntry.getName() + " from " + jarFile.getAbsolutePath()); } finally { byteArrayStream.close(); } } } finally { if (jarFileWrapper != null) { try { jarFileWrapper.close(); } catch (Exception ignore) { logger.debug(ignore); } } } } return entries; }
private TreeSet<String> findClasses(String directory, String packageName) throws IOException { TreeSet<String> classes = new TreeSet<String>(); if (directory.startsWith("file:") && directory.contains("!")) { String[] split = directory.split("!"); URL jar = new URL(split[0]); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry entry = null; while ((entry = zip.getNextEntry()) != null) { if (entry.getName().startsWith("husacct/validate/domain/validation/ruletype") && entry.getName().endsWith(".class")) { final String className = entry.getName().replaceAll("[$].*", "").replaceAll("[.]class", "").replace('/', '.'); classes.add(className); } } } File dir = new File(URLDecoder.decode(directory, "UTF-8")); if (!dir.exists()) { return classes; } File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file.getAbsolutePath(), packageName + "." + file.getName())); } else if (file.getName().endsWith(".class")) { classes.add(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)); } } return classes; }
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()); } } }
protected void unzip(String pathToFile, String outputFolder) { System.out.println("Start unzipping: " + pathToFile + " to " + outputFolder); String pathToUnzip; if (outputFolder.equals(pathManager.getPlatformFolderInAndroidSdk())) { pathToUnzip = outputFolder; } else { pathToUnzip = outputFolder + "/" + FileUtil.getNameWithoutExtension(new File(pathToFile)); } if (new File(pathToUnzip).listFiles() != null) { System.out.println("File was already unzipped: " + pathToFile); return; } try { byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; zipinputstream = new ZipInputStream(new FileInputStream(pathToFile)); zipentry = zipinputstream.getNextEntry(); try { while (zipentry != null) { String entryName = zipentry.getName(); int n; File outputFile = new File(outputFolder + "/" + entryName); if (zipentry.isDirectory()) { outputFile.mkdirs(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); continue; } else { File parentFile = outputFile.getParentFile(); if (parentFile != null && !parentFile.exists()) { parentFile.mkdirs(); } outputFile.createNewFile(); } FileOutputStream fileoutputstream = new FileOutputStream(outputFile); try { while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } } finally { fileoutputstream.close(); } zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (IOException e) { System.err.println("Entry name: " + zipentry.getName()); e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Finish unzipping: " + pathToFile + " to " + outputFolder); }
protected static File file(final File root, final ZipEntry entry) throws IOException { if (root == null) { throw new NullPointerException("root"); } if (!root.isDirectory()) { throw new IllegalArgumentException("root is not an existing directory"); } if (entry == null) { throw new NullPointerException("entry"); } final File file = new File(root, entry.getName()); File parent = file; if (!entry.isDirectory()) { final String name = entry.getName(); final int index = name.lastIndexOf('/'); if (index != -1) { parent = new File(root, name.substring(0, index)); } } if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { throw new IOException("failed to create a directory: " + parent.getPath()); } return file; }
/** * Add the entries from the supplied {@link ZipInputStream} to this archive instance. * * @param zipStream The zip stream. * @return This archive instance. * @throws IOException Error reading zip stream. */ public Archive addEntries(ZipInputStream zipStream) throws IOException { AssertArgument.isNotNull(zipStream, "zipStream"); try { ZipEntry zipEntry = zipStream.getNextEntry(); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); byte[] byteReadBuffer = new byte[512]; int byteReadCount; while (zipEntry != null) { if (zipEntry.isDirectory()) { addEntry(zipEntry.getName(), (byte[]) null); } else { while ((byteReadCount = zipStream.read(byteReadBuffer)) != -1) { outByteStream.write(byteReadBuffer, 0, byteReadCount); } addEntry(zipEntry.getName(), outByteStream.toByteArray()); outByteStream.reset(); } zipEntry = zipStream.getNextEntry(); } } finally { try { zipStream.close(); } catch (IOException e) { logger.debug("Unexpected error closing EDI Mapping Model Zip stream.", e); } } return this; }
private void checkLoadedModForPermissionClass(File modFile) { try { Pattern p = Pattern.compile("permission", Pattern.CASE_INSENSITIVE); if (modFile.isDirectory()) { for (File file : modFile.listFiles()) { checkLoadedModForPermissionClass(file); } } else if ((modFile.getName().endsWith(".zip")) || (modFile.getName().endsWith(".jar"))) { ZipFile zip = new ZipFile(modFile); Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry zipentry = (ZipEntry) entries.nextElement(); if (zipentry != null && zipentry.getName().endsWith(".class") && p.matcher(zipentry.getName()).find()) { checkLoadedClass(zip.getInputStream(zipentry)); } } zip.close(); } else if (modFile.getName().endsWith(".class") && p.matcher(modFile.getName()).find()) { checkLoadedClass(new FileInputStream(modFile)); } } catch (IOException e) { } }
protected void init() throws IOException { for (int i = 0; i < urls.length; i++) { Set<String> files = new HashSet<String>(500); URLConnection c = urls[i].openConnection(); ByteArrayOutputStream baos = new ByteArrayOutputStream(20000); ZipInputStream zis = new ZipInputStream(c.getInputStream()); ZipEntry ze = zis.getNextEntry(); while (ze != null) { int start = baos.size(); startPosition.put(ze.getName(), start); RepositoryHelp.streamCopy(zis, baos, false); int end = baos.size(); lengths.put(ze.getName(), end - start); files.add(ze.getName()); ze = zis.getNextEntry(); } zis.close(); baos.close(); byte[] theFile = baos.toByteArray(); for (String name : files) { memoryMappedFiles.put(name, theFile); } log("mapped file: " + urls[i]); } }