java.util.zip.ZipFile Java Examples
The following examples show how to use
java.util.zip.ZipFile.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZipUtils.java From MyBookshelf with GNU General Public License v3.0 | 6 votes |
private static boolean unzipChildFile(final File destDir, final List<File> files, final ZipFile zip, final ZipEntry entry, final String name) throws IOException { File file = new File(destDir, name); files.add(file); if (entry.isDirectory()) { return createOrExistsDir(file); } else { if (!createOrExistsFile(file)) return false; try (InputStream in = new BufferedInputStream(zip.getInputStream(entry)); OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { byte buffer[] = new byte[BUFFER_LEN]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } } return true; }
Example #2
Source File: Input.java From JRemapper with MIT License | 6 votes |
/** * Populates class and resource maps. * * @throws IOException * Thrown if the archive could not be read, or an internal file * could not be read. */ protected Map<String, byte[]> readArchive() throws IOException { Map<String, byte[]> contents = new HashMap<>(); try (ZipFile file = new ZipFile(jarFile)) { // iterate zip entries Enumeration<? extends ZipEntry> entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // skip directories if (entry.isDirectory()) continue; try (InputStream is = file.getInputStream(entry)) { // add as class, or resource if not a class file. String name = entry.getName(); if (name.endsWith(".class")) { addClass(name, is); } else { addResource(name, is); } } } } return contents; }
Example #3
Source File: BundlesInstaller.java From ACDD with MIT License | 6 votes |
private boolean installBundle(ZipFile zipFile, String location, Application application) { log.info("processLibsBundle entryName " + location); this.bundleDebug.installExternalBundle(location); String fileNameFromEntryName = Utils.getFileNameFromEntryName(location); String packageNameFromEntryName = Utils.getPackageNameFromEntryName(location); if (packageNameFromEntryName == null || packageNameFromEntryName.length() <= 0) { return false; } File archvieFile = new File(new File(application.getFilesDir().getParentFile(), "lib"), fileNameFromEntryName); if (OpenAtlas.getInstance().getBundle(packageNameFromEntryName) != null) { return false; } try { if (archvieFile.exists()) { OpenAtlas.getInstance().installBundle(packageNameFromEntryName, archvieFile); } else { OpenAtlas.getInstance().installBundle(packageNameFromEntryName, zipFile.getInputStream(zipFile.getEntry(location))); } log.info("Succeed to install bundle " + packageNameFromEntryName); return true; } catch (Throwable e) { Log.e("BundlesInstaller", "Could not install bundle.", e); return false; } }
Example #4
Source File: ResourceLocator.java From open-ig with GNU Lesser General Public License v3.0 | 6 votes |
/** @return open a completely new input stream to the given resource (to avoid sharing a single zip file.) */ public InputStream openNew() { try { if (zipContainer) { final ZipFile zf = new ZipFile(container); final InputStream in = zf.getInputStream(zf.getEntry(fileName)); BufferedInputStream bin = new BufferedInputStream(in) { @Override public void close() throws IOException { super.close(); zf.close(); } }; return bin; } return new FileInputStream(container + "/" + fileName); } catch (IOException ex) { throw new RuntimeException(ex); } }
Example #5
Source File: ZipParser.java From bubble with MIT License | 6 votes |
@Override public void parse(File file) throws IOException { mZipFile = new ZipFile(file.getAbsolutePath()); mEntries = new ArrayList<ZipEntry>(); Enumeration<? extends ZipEntry> e = mZipFile.entries(); while (e.hasMoreElements()) { ZipEntry ze = e.nextElement(); if (!ze.isDirectory() && Utils.isImage(ze.getName())) { mEntries.add(ze); } } Collections.sort(mEntries, new NaturalOrderComparator() { @Override public String stringValue(Object o) { return ((ZipEntry) o).getName(); } }); }
Example #6
Source File: ZipUtils.java From wildfly-core with GNU Lesser General Public License v2.1 | 6 votes |
/** * unpack... * * @param zip the zip * @param patchDir the patch dir * @throws IOException */ private static void unzip(final ZipFile zip, final File patchDir) throws IOException { final Enumeration<? extends ZipEntry> entries = zip.entries(); while(entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); final String name = entry.getName(); final File current = new File(patchDir, name); if(entry.isDirectory()) { continue; } else { if(! current.getParentFile().exists()) { current.getParentFile().mkdirs(); } try (final InputStream eis = zip.getInputStream(entry)){ Files.copy(eis, current.toPath()); //copy(eis, current); } } } }
Example #7
Source File: BundleModuleMergerTest.java From bundletool with Apache License 2.0 | 6 votes |
@Test public void testMultipleModulesWithInstallTime_bundleToolVersionOverride() throws Exception { XmlNode installTimeModuleManifest = androidManifestForFeature("com.test.app.detail", withInstallTimeDelivery()); createBasicZipBuilder(BUNDLE_CONFIG_0_14_0) .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST) .addFileWithContent(ZipPath.create("base/dex/classes.dex"), DUMMY_CONTENT) .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), DUMMY_CONTENT) .addFileWithProtoContent( ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest) .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), DUMMY_CONTENT) .writeTo(bundleFile); try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) { AppBundle appBundle = BundleModuleMerger.mergeNonRemovableInstallTimeModules( AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ true); assertThat(appBundle.getFeatureModules().keySet()) .comparingElementsUsing(equalsBundleModuleName()) .containsExactly("base"); } }
Example #8
Source File: DalvikStatsTool.java From buck with Apache License 2.0 | 6 votes |
/** CLI wrapper to run against every class in a set of JARs. */ public static void main(String[] args) throws IOException { ImmutableSet.Builder<DalvikMemberReference> allFields = ImmutableSet.builder(); for (String fname : args) { try (ZipFile inJar = new ZipFile(fname)) { for (ZipEntry entry : Collections.list(inJar.entries())) { if (!entry.getName().endsWith(".class")) { continue; } InputStream rawClass = inJar.getInputStream(entry); Stats stats = getEstimate(rawClass); System.out.println( stats.estimatedLinearAllocSize + "\t" + entry.getName().replace(".class", "")); allFields.addAll(stats.fieldReferences); } } } // Uncomment to debug fields. // System.out.println(); // // for (DalvikMemberReference field : allFields.build()) { // System.out.println(field); // } }
Example #9
Source File: FurnaceClasspathScanner.java From windup with Eclipse Public License 1.0 | 6 votes |
/** * Scans given archive for files passing given filter, adds the results into given list. */ private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles) { try { try (ZipFile zip = new ZipFile(archive)) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (filter.accept(name)) discoveredFiles.add(name); } } } catch (IOException e) { throw new RuntimeException("Error handling file " + archive, e); } }
Example #10
Source File: MultiThreadedReadTest.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
public static void main(String args[]) throws Exception { createZipFile(); try (ZipFile zf = new ZipFile(new File(ZIPFILE_NAME))) { is = zf.getInputStream(zf.getEntry(ZIPENTRY_NAME)); Thread[] threadArray = new Thread[NUM_THREADS]; for (int i = 0; i < threadArray.length; i++) { threadArray[i] = new MultiThreadedReadTest(); } for (int i = 0; i < threadArray.length; i++) { threadArray[i].start(); } for (int i = 0; i < threadArray.length; i++) { threadArray[i].join(); } } finally { FileUtils.deleteFileIfExistsWithRetry(Paths.get(ZIPFILE_NAME)); } }
Example #11
Source File: Dex.java From Box with Apache License 2.0 | 6 votes |
/** * Creates a new dex buffer from the dex file {@code file}. */ public Dex(File file) throws IOException { if (FileUtils.hasArchiveSuffix(file.getName())) { ZipFile zipFile = new ZipFile(file); ZipEntry entry = zipFile.getEntry(DexFormat.DEX_IN_JAR_NAME); if (entry != null) { try (InputStream inputStream = zipFile.getInputStream(entry)) { loadFrom(inputStream); } zipFile.close(); } else { throw new DexException("Expected " + DexFormat.DEX_IN_JAR_NAME + " in " + file); } } else if (file.getName().endsWith(".dex")) { try (InputStream inputStream = new FileInputStream(file)) { loadFrom(inputStream); } } else { throw new DexException("unknown output extension: " + file); } }
Example #12
Source File: EnvironmentUtils.java From The-5zig-Mod with MIT License | 6 votes |
private static ZipFile getZipFile(URL url) { try { URI uri = url.toURI(); File file = new File(uri); ZipFile zipFile = new ZipFile(file); if (zipFile.getEntry("eu/the5zig/mod/The5zigMod.class") == null) { zipFile.close(); return null; } return zipFile; } catch (Exception ignored) { return null; } }
Example #13
Source File: SongPack.java From Quelea with GNU General Public License v3.0 | 6 votes |
/** * Create a new song pack from a file. * * @param file the file to create the song pack from. * @return the song pack that's been created * @throws IOException if something went wrong. */ public static SongPack fromFile(File file) throws IOException { try (ZipFile zipFile = new ZipFile(file, Charset.forName("UTF-8"))) { SongPack ret = new SongPack(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { try { ZipEntry entry = entries.nextElement(); SongDisplayable song = SongDisplayable.parseXML(zipFile.getInputStream(entry)); if (song != null) { ret.addSong(song); } } catch (Exception ex) { //Skipping malformed song... } } return ret; } }
Example #14
Source File: ClearStaleZipFileInputStreams.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
private static void runTest(int compression) throws Exception { ReferenceQueue<InputStream> rq = new ReferenceQueue<>(); System.out.println("Testing with a zip file with compression level = " + compression); File f = createTestFile(compression); try (ZipFile zf = new ZipFile(f)) { Set<Object> refSet = createTransientInputStreams(zf, rq); System.out.println("Waiting for 'stale' input streams from ZipFile to be GC'd ..."); System.out.println("(The test will hang on failure)"); while (false == refSet.isEmpty()) { refSet.remove(rq.remove()); } System.out.println("Test PASSED."); System.out.println(); } finally { f.delete(); } }
Example #15
Source File: Dex.java From atlas with Apache License 2.0 | 6 votes |
/** * Creates a new dex buffer from the dex file {@code file}. */ public Dex(File file) throws IOException{ if (FileUtils.hasArchiveSuffix(file.getName())) { ZipFile zipFile = new ZipFile(file); ZipEntry entry = zipFile.getEntry(DexFormat.DEX_IN_JAR_NAME); if (entry != null) { loadFrom(zipFile.getInputStream(entry)); zipFile.close(); } else { throw new DexException2("Expected " + DexFormat.DEX_IN_JAR_NAME + " in " + file); } } else if (file.getName().endsWith(".dex")) { loadFrom(new FileInputStream(file)); } else { throw new DexException2("unknown output extension: " + file); } }
Example #16
Source File: Utils.java From netbeans-mmd-plugin with Apache License 2.0 | 6 votes |
/** * Read who;e zip item into byte array. * * @param zipFile zip file * @param path path to resource * @return byte array or null if not found * @throws IOException thrown if there is any transport error */ @Nullable public static byte[] toByteArray(@Nonnull final ZipFile zipFile, @Nonnull final String path) throws IOException { final InputStream in = findInputStreamForResource(zipFile, path); byte[] result = null; if (in != null) { try { result = IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } } return result; }
Example #17
Source File: XposedHelpers.java From kcanotify_h5-master with GNU General Public License v3.0 | 5 votes |
/** * Invokes the {@link ZipFile#close()} method, ignoring IOExceptions. */ /*package*/ static void closeSilently(final ZipFile zipFile) { if (zipFile != null) { try { zipFile.close(); } catch (final IOException ignored) { } } }
Example #18
Source File: RxZipTool.java From RxTools-master with Apache License 2.0 | 5 votes |
public static String zipEncrypt(String src, String dest, boolean isCreateDir, String passwd) { File srcFile = new File(src); dest = buildDestinationZipFilePath(srcFile, dest); ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式 parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 压缩级别 if (!RxDataTool.isNullString(passwd)) { parameters.setEncryptFiles(true); parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密方式 parameters.setPassword(passwd.toCharArray()); } try { net.lingala.zip4j.core.ZipFile zipFile = new net.lingala.zip4j.core.ZipFile(dest); if (srcFile.isDirectory()) { // 如果不创建目录的话,将直接把给定目录下的文件压缩到压缩文件,即没有目录结构 if (!isCreateDir) { File [] subFiles = srcFile.listFiles(); ArrayList<File> temp = new ArrayList<File>(); Collections.addAll(temp, subFiles); zipFile.addFiles(temp, parameters); return dest; } zipFile.addFolder(srcFile, parameters); } else { zipFile.addFile(srcFile, parameters); } return dest; } catch (ZipException e) { e.printStackTrace(); } return null; }
Example #19
Source File: ZipConfigFileHandler.java From LicenseScout with Apache License 2.0 | 5 votes |
private InputStream getInputStream(final String entryName) throws IOException { try (ZipFile zipFile = new ZipFile(artifactFile)) { ZipEntry entry = zipFile.getEntry(entryName); InputStream zipInputStream = zipFile.getInputStream(entry); //Read the zip input stream fully into memory byte[] buffer = IOUtils.toByteArray(zipInputStream); return new ByteArrayInputStream(buffer); } }
Example #20
Source File: BootstrapClassLoader.java From furnace with Eclipse Public License 1.0 | 5 votes |
@SuppressWarnings("deprecation") private List<URL> handleZipFile(File file) throws IOException { File tempDir = OperatingSystemUtils.createTempDir(); List<URL> result = new ArrayList<>(); try { ZipFile zip = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (name.matches(path + "/.*\\.jar")) { log.log(Level.FINE, String.format("ZipEntry detected: %s len %d added %TD", file.getAbsolutePath() + "/" + entry.getName(), entry.getSize(), new Date(entry.getTime()))); result.add(copy(tempDir, entry.getName(), JarLocator.class.getClassLoader().getResource(name).openStream() ).toURL()); } } zip.close(); } catch (ZipException e) { throw new RuntimeException("Error handling file " + file, e); } return result; }
Example #21
Source File: DefaultModuleRegistry.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 5 votes |
private Properties loadModuleProperties(String name, File jarFile) { try { ZipFile zipFile = new ZipFile(jarFile); try { ZipEntry entry = zipFile.getEntry(String.format("%s-classpath.properties", name)); return GUtil.loadProperties(zipFile.getInputStream(entry)); } finally { zipFile.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } }
Example #22
Source File: SystemUtils.java From VideoMeeting with Apache License 2.0 | 5 votes |
/** * 返回编译时间 * * @return -1: unknown time. */ public static long getBuildTime(Context ctx) { try { ApplicationInfo ai = ctx.getApplicationInfo(); ZipFile zf = new ZipFile(ai.sourceDir); ZipEntry ze = zf.getEntry("classes.dex"); long time = ze.getTime(); zf.close(); return time; } catch (Exception e) { return -1; } }
Example #23
Source File: NestedZipEntryJavaFileObject.java From spring-cloud-function with Apache License 2.0 | 5 votes |
public NestedZipEntryJavaFileObject(File outerFile, ZipFile outerZipFile, ZipEntry innerZipFile, ZipEntry innerZipFileEntry) { this.outerFile = outerFile; this.outerZipFile = outerZipFile; this.innerZipFile = innerZipFile; this.innerZipFileEntry = innerZipFileEntry; }
Example #24
Source File: ApkBreakdownGenerator.java From bundletool with Apache License 2.0 | 5 votes |
private ImmutableMap<String, Long> calculateDownloadSizePerEntry(ZipFile zipFile) throws IOException { ImmutableList<ByteSource> streams = zipFile.stream() .map(zipStreamEntry -> ZipUtils.asByteSource(zipFile, zipStreamEntry)) .collect(toImmutableList()); ImmutableList<Long> downloadSizes = compressedSizeCalculator.calculateGZipSizeForEntries(streams); return Streams.zip(zipFile.stream(), downloadSizes.stream(), AbstractMap.SimpleEntry::new) .collect( toImmutableMap(entry -> entry.getKey().getName(), AbstractMap.SimpleEntry::getValue)); }
Example #25
Source File: ClasspathScanner.java From kylin with Apache License 2.0 | 5 votes |
public static void main(final String[] args) { ClasspathScanner scanner = new ClasspathScanner(); if (args.length == 0) { for (File f : scanner.rootResources) { System.out.println(f.getAbsolutePath()); } System.exit(0); } final int[] hitCount = new int[1]; scanner.scan("", new ResourceVisitor() { public void accept(File dir, String relativeFileName) { check(dir.getAbsolutePath(), relativeFileName.replace('\\', '/')); } public void accept(ZipFile archive, ZipEntry zipEntry) { check(archive.getName(), zipEntry.getName().replace('\\', '/')); } private void check(String base, String relativePath) { boolean hit = false; for (int i = 0; i < args.length && !hit; i++) { hit = relativePath.contains(args[i]) || match(args[i], relativePath); } if (hit) { System.out.println(base + " - " + relativePath); hitCount[0]++; } } }); int exitCode = hitCount[0] > 0 ? 0 : 1; System.exit(exitCode); }
Example #26
Source File: ZipUtils.java From iMoney with Apache License 2.0 | 5 votes |
/** * 解压缩一个文件 * * @param zipFile 压缩文件 * @param folderPath 解压缩的目标目录 * @throws IOException 当解压缩过程出错时抛出 */ public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException { File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdirs(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) { ZipEntry entry = ((ZipEntry) entries.nextElement()); InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = new String(str.getBytes("8859_1"), "GB2312"); File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); } }
Example #27
Source File: ZipUtils.java From MyBookshelf with GNU General Public License v3.0 | 5 votes |
/** * Return the files' comment in ZIP file. * * @param zipFile The ZIP file. * @return the files' comment in ZIP file * @throws IOException if an I/O error has occurred */ public static List<String> getComments(final File zipFile) throws IOException { if (zipFile == null) return null; List<String> comments = new ArrayList<>(); ZipFile zip = new ZipFile(zipFile); Enumeration<?> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = ((ZipEntry) entries.nextElement()); comments.add(entry.getComment()); } zip.close(); return comments; }
Example #28
Source File: ZipFileUtils.java From code-generator with Apache License 2.0 | 5 votes |
public static Map<String, TemplateGroup> readTemplateFromFile(String path) { Gson gson = new Gson(); Map<String, TemplateGroup> templateGroupMap = Maps.newHashMap(); try { ZipFile zipFile = new ZipFile(path); Enumeration<? extends ZipEntry> entries = zipFile.entries(); // todo multi group import while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); if (zipEntry.isDirectory()) { continue; } if (!zipEntry.getName().matches(".+/[^/]+\\.json")) { throw new IllegalArgumentException("invalid template file"); } String[] name = zipEntry.getName().split("/"); TemplateGroup templateGroup; if (templateGroupMap.containsKey(name[0])) { templateGroup = templateGroupMap.get(name[0]); } else { templateGroup = new TemplateGroup(name[0]); } Template template = gson .fromJson(new InputStreamReader(zipFile.getInputStream(zipEntry)), Template.class); templateGroup.addTemplate(template); templateGroupMap.put(templateGroup.getName(), templateGroup); } return templateGroupMap; } catch (IOException e) { e.printStackTrace(); } return null; }
Example #29
Source File: Comment.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
private static void verifyZipFile(String name, String comment) throws Exception { // Check that Zip entry was correctly written. try (ZipFile zipFile = new ZipFile(name)) { ZipEntry zipEntry = zipFile.getEntry(entryName); InputStream is = zipFile.getInputStream(zipEntry); String result = new DataInputStream(is).readUTF(); if (!result.equals(entryContents)) throw new Exception("Entry contents corrupted"); } try (RandomAccessFile file = new RandomAccessFile(name, "r")) { // Check that comment length was correctly written. file.seek(file.length() - comment.length() - ZipFile.ENDHDR + ZipFile.ENDCOM); int b1 = file.readUnsignedByte(); int b2 = file.readUnsignedByte(); if (b1 + (b2 << 8) != comment.length()) throw new Exception("Zip file comment length corrupted"); // Check that comment was correctly written. file.seek(file.length() - comment.length()); byte [] bytes = new byte [comment.length()]; file.readFully(bytes); if (! comment.equals(new String(bytes, "UTF8"))) throw new Exception("Zip file comment corrupted"); } }
Example #30
Source File: ZipUtils.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
/** * Unzip. * * @param zipFile the zip file * @param destDir the dest dir */ public static void unzip(ZipFile zipFile, File destDir) { Enumeration entries; try { entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { File destFile = new File(destDir,entry.getName()); File destFileDir = destFile.getParentFile(); if(!destFileDir.exists()) { System.err.println("Extracting directory: " + entry.getName().substring(0, entry.getName().lastIndexOf('/'))); destFileDir.mkdirs(); } System.err.println("Extracting file: " + entry.getName()); copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream( new File(destDir,entry.getName())))); } } zipFile.close(); } catch (IOException ioe) { System.err.println("Unhandled exception:"); ioe.printStackTrace(); return; } }