Java Code Examples for java.util.zip.ZipFile#entries()
The following examples show how to use
java.util.zip.ZipFile#entries() .
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: ToolSupport.java From raccoon4 with Apache License 2.0 | 6 votes |
private void unzip(File file) throws IOException { ZipFile zipFile = new ZipFile(file); try { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(binDir, entry.getName()); if (entry.isDirectory()) entryDestination.mkdirs(); else { entryDestination.getParentFile().mkdirs(); InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination); IOUtils.copy(in, out); IOUtils.closeQuietly(in); out.close(); } } } finally { zipFile.close(); } }
Example 2
Source File: ZipUtils.java From xiaoyaoji with GNU General Public License v3.0 | 6 votes |
/** * 解压缩 * * @param file * @param outputDir * @throws IOException */ public static void uncompression(File file, String outputDir) throws IOException { ZipFile zipFile = new ZipFile(file); try { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(outputDir, entry.getName()); if (entry.isDirectory()) { entryDestination.mkdirs(); } else { entryDestination.getParentFile().mkdirs(); InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } finally { zipFile.close(); } }
Example 3
Source File: ZipFileUtils.java From apk-dependency-graph with Apache License 2.0 | 6 votes |
public static List<String> filterByExtension( final String zipFilePath, final String extension) throws IOException { List<String> files = new ArrayList<>(); ZipFile zipFile = new ZipFile(zipFilePath); Enumeration zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement(); if (!zipEntry.isDirectory()) { String fileName = zipEntry.getName(); if (checkExtension(fileName, extension)) { files.add(fileName); } } } return files; }
Example 4
Source File: Reflection.java From OpenDA with GNU Lesser General Public License v3.0 | 6 votes |
private void processOneZip(String zipFileName) { //System.out.println("processing archive:"+zipFileName); try { ZipFile zippy = new ZipFile(new File(zipFileName)); Enumeration all = zippy.entries(); // For each entry, get its name and put it into "entries" while (all.hasMoreElements()) { String className = ((ZipEntry)(all.nextElement())).getName(); className=className.replaceAll("/","."); if(className.endsWith(".class")){ className=className.replace(".class", ""); if(matchesFilterList(className)){ this.classCache.add(className); } } } } catch (IOException err) { throw new RuntimeException("Problem opening archive :"+zipFileName); } }
Example 5
Source File: DataLoader.java From stendhal with GNU General Public License v2.0 | 6 votes |
/** * adds a .jar file to the repository * * @param filename name of .jar file */ public static void addJarFile(String filename) { try { if (knownFiles.contains(filename)) { return; } File file = new File(filename); if (!file.canRead()) { return; } knownFiles.add(filename); ZipFile zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { String name = stripLeadingSlash(entry.getName()); contentFilenameMapping.put(name, file); contentZipFilesMapping.put(name, zipFile); } } } catch (IOException e) { logger.error(e, e); } }
Example 6
Source File: TestUtil.java From netbeans with Apache License 2.0 | 6 votes |
public static void unzip( ZipFile zip, File dest ) throws IOException { for( Enumeration<? extends ZipEntry> e = zip.entries(); e.hasMoreElements(); ) { ZipEntry entry = e.nextElement(); File f = new File( dest, entry.getName() ); if ( entry.isDirectory() ) { f.mkdirs(); } else { f.getParentFile().mkdirs(); f.createNewFile(); BufferedInputStream bis = new BufferedInputStream( zip.getInputStream( entry ) ); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( f ) ); copyFile( bis, bos ); } } }
Example 7
Source File: ZipUtils.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
/** * Gets the directory name by level. * * @param zipFile the zip file * @param levelNo the level no * * @return the directory name by level */ public static String[] getDirectoryNameByLevel(ZipFile zipFile, int levelNo) { Set names = new HashSet(); Enumeration entries; try { entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String fileName = entry.getName(); String[] components = fileName.split("/"); if(components.length == (levelNo+1)) { String dirNam = components[components.length-2]; names.add(dirNam); } System.out.println(entry.getName()); } } zipFile.close(); } catch (IOException ioe) { System.err.println("Unhandled exception:"); ioe.printStackTrace(); return null; } return (String[])names.toArray(new String[0]); }
Example 8
Source File: ClasspathAddMvnDepsCellMagicCommandTest.java From beakerx with Apache License 2.0 | 5 votes |
private static void unzipRepo() { try { ZipFile zipFile = new ZipFile(BUILD_PATH + "/testMvnCache.zip"); Enumeration<?> enu = zipFile.entries(); while (enu.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) enu.nextElement(); String name = BUILD_PATH + "/" + zipEntry.getName(); File file = new File(name); if (name.endsWith("/")) { file.mkdirs(); continue; } File parent = file.getParentFile(); if (parent != null) { parent.mkdirs(); } InputStream is = zipFile.getInputStream(zipEntry); FileOutputStream fos = new FileOutputStream(file); byte[] bytes = new byte[1024]; int length; while ((length = is.read(bytes)) >= 0) { fos.write(bytes, 0, length); } is.close(); fos.close(); } zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } }
Example 9
Source File: ClearStaleZipFileInputStreams.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private static Set<Object> createTransientInputStreams(ZipFile zf, ReferenceQueue<InputStream> rq) throws Exception { Enumeration<? extends ZipEntry> zfe = zf.entries(); Set<Object> refSet = new HashSet<>(); while (zfe.hasMoreElements()) { InputStream is = zf.getInputStream(zfe.nextElement()); refSet.add(new WeakReference<InputStream>(is, rq)); } return refSet; }
Example 10
Source File: FileUtil.java From hadoop with Apache License 2.0 | 5 votes |
/** * Given a File input it will unzip the file in a the unzip directory * passed as the second parameter * @param inFile The zip file as input * @param unzipDir The unzip directory where to unzip the zip file. * @throws IOException */ public static void unZip(File inFile, File unzipDir) throws IOException { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(inFile); try { entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { InputStream in = zipFile.getInputStream(entry); try { File file = new File(unzipDir, entry.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 { in.close(); } } } } finally { zipFile.close(); } }
Example 11
Source File: FileUtil.java From hadoop-gpu with Apache License 2.0 | 5 votes |
/** * Given a File input it will unzip the file in a the unzip directory * passed as the second parameter * @param inFile The zip file as input * @param unzipDir The unzip directory where to unzip the zip file. * @throws IOException */ public static void unZip(File inFile, File unzipDir) throws IOException { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(inFile); try { entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { InputStream in = zipFile.getInputStream(entry); try { File file = new File(unzipDir, entry.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 { in.close(); } } } } finally { zipFile.close(); } }
Example 12
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 13
Source File: JarLoader.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public ClasspathCache.LoaderData buildData() throws IOException { ZipFile zipFile = getZipFile(); try { ClasspathCache.LoaderDataBuilder loaderDataBuilder = new ClasspathCache.LoaderDataBuilder(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (name.endsWith(UrlClassLoader.CLASS_EXTENSION)) { loaderDataBuilder.addClassPackageFromName(name); } else { loaderDataBuilder.addResourcePackageFromName(name); } loaderDataBuilder.addPossiblyDuplicateNameEntry(name); } return loaderDataBuilder.build(); } finally { releaseZipFile(zipFile); } }
Example 14
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 15
Source File: ReportingTest.java From blynk-server with GNU General Public License v3.0 | 4 votes |
@Test public void testFinalFileNameCSVMerged2DataStreamWithNameCorrectEscaping2() throws Exception { Device device1 = new Device(2, "My Device2 with, big name", BoardType.ESP8266); clientPair.appClient.createDevice(1, device1); String tempDir = holder.props.getProperty("data.folder"); Path userReportFolder = Paths.get(tempDir, "data", getUserName()); if (Files.notExists(userReportFolder)) { Files.createDirectories(userReportFolder); } Path pinReportingDataPath10 = Paths.get(tempDir, "data", getUserName(), ReportingDiskDao.generateFilename(1, 0, PinType.VIRTUAL, (short) 1, GraphGranularityType.MINUTE)); Path pinReportingDataPath20 = Paths.get(tempDir, "data", getUserName(), ReportingDiskDao.generateFilename(1, 0, PinType.VIRTUAL, (short) 2, GraphGranularityType.MINUTE)); long pointNow = System.currentTimeMillis(); FileUtils.write(pinReportingDataPath10, 1.11D, pointNow); FileUtils.write(pinReportingDataPath20, 1.12D, pointNow); Path pinReportingDataPath12 = Paths.get(tempDir, "data", getUserName(), ReportingDiskDao.generateFilename(1, 2, PinType.VIRTUAL, (short) 1, GraphGranularityType.MINUTE)); Path pinReportingDataPath22 = Paths.get(tempDir, "data", getUserName(), ReportingDiskDao.generateFilename(1, 2, PinType.VIRTUAL, (short) 2, GraphGranularityType.MINUTE)); FileUtils.write(pinReportingDataPath12, 1.13D, pointNow); FileUtils.write(pinReportingDataPath22, 1.14D, pointNow); ReportDataStream reportDataStream = new ReportDataStream((short) 1, PinType.VIRTUAL, "Temperature", true); ReportDataStream reportDataStream2 = new ReportDataStream((short) 2, PinType.VIRTUAL, "Humidity", true); ReportSource reportSource = new TileTemplateReportSource( new ReportDataStream[] {reportDataStream, reportDataStream2}, 1, new int[] {0, 2} ); ReportingWidget reportingWidget = new ReportingWidget(); reportingWidget.height = 1; reportingWidget.width = 1; reportingWidget.reportSources = new ReportSource[] { reportSource }; clientPair.appClient.createWidget(1, reportingWidget); clientPair.appClient.verifyResult(ok(2)); //a bit upfront long now = System.currentTimeMillis() + 1000; LocalTime localTime = LocalTime.ofInstant(Instant.ofEpochMilli(now), ZoneId.of("UTC")); localTime = LocalTime.of(localTime.getHour(), localTime.getMinute()); Report report = new Report(1, "DailyReport", new ReportSource[] {reportSource}, new DailyReport(now, ReportDurationType.INFINITE, 0, 0), "[email protected]", GraphGranularityType.MINUTE, true, MERGED_CSV, Format.ISO_SIMPLE, ZoneId.of("UTC"), 0, 0, null); clientPair.appClient.createReport(1, report); report = clientPair.appClient.parseReportFromResponse(3); assertNotNull(report); assertEquals(System.currentTimeMillis(), report.nextReportAt, 5000); String date = LocalDate.now(report.tzName).toString(); String filename = getUserName() + "_Blynk_" + report.id + "_" + date + ".zip"; String downloadUrl = "http://127.0.0.1:18080/" + filename; verify(holder.mailWrapper, timeout(3000)).sendReportEmail(eq("[email protected]"), eq("Your daily DailyReport is ready"), eq(downloadUrl), eq("Report name: DailyReport<br>Period: Daily, at " + localTime)); sleep(200); assertEquals(1, holder.reportScheduler.getCompletedTaskCount()); assertEquals(2, holder.reportScheduler.getTaskCount()); Path result = Paths.get(FileUtils.CSV_DIR, getUserName() + "_" + AppNameUtil.BLYNK + "_" + report.id + "_" + date + ".zip"); assertTrue(Files.exists(result)); ZipFile zipFile = new ZipFile(result.toString()); Enumeration<? extends ZipEntry> entries = zipFile.entries(); assertTrue(entries.hasMoreElements()); ZipEntry entry = entries.nextElement(); assertNotNull(entry); assertEquals("DailyReport.csv", entry.getName()); String nowFormatted = DateTimeFormatter .ofPattern(Format.ISO_SIMPLE.pattern) .withZone(ZoneId.of("UTC")) .format(Instant.ofEpochMilli(pointNow)); String resultCsvString = readStringFromZipEntry(zipFile, entry); assertNotNull(resultCsvString); assertEquals(resultCsvString, nowFormatted + ",Temperature,My Device,1.11\n" + nowFormatted + ",Humidity,My Device,1.12\n" + nowFormatted + ",Temperature,\"My Device2 with, big name\",1.13\n" + nowFormatted + ",Humidity,\"My Device2 with, big name\",1.14\n"); }
Example 16
Source File: ComPluginInstallerImpl.java From openemm with GNU Affero General Public License v3.0 | 4 votes |
private void fillBirtZipFile( FileOutputStream fileOutputStream, ZipFile zipFile, String pluginId) throws IOException { final String subdirectoryName = ComExtensionConstants.PLUGIN_BIRT_ZIP_BASE; if( logger.isDebugEnabled()) { logger.debug( "Creating BIRT zip file for plugin '" + pluginId + "'"); } try (ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) { String entryNameStart = FileUtils.removeTrailingSeparator( subdirectoryName) + "/"; Enumeration<? extends ZipEntry> entries = zipFile.entries(); ZipEntry entry = null; String translatedName; while( entries.hasMoreElements()) { entry = entries.nextElement(); if( !entry.getName().startsWith( entryNameStart)) { continue; } translatedName = entry.getName().substring( entryNameStart.length()); if( !entry.isDirectory()) { if( logger.isDebugEnabled()) { logger.debug( "Packing " + entry.getName() + " as " + translatedName); } // Transfer file to temporary ZIP file try (InputStream inputStream = zipFile.getInputStream(entry)) { zipOutputStream.putNextEntry( new ZipEntry( translatedName)); try { FileUtils.streamToStream( inputStream, entry.getSize(), zipOutputStream); } finally { zipOutputStream.closeEntry(); } } } } } }
Example 17
Source File: FrameworkPacker.java From birt with Eclipse Public License 1.0 | 4 votes |
protected void packZip( ZipOutputStream output, BundleEntry bundleEntry, ZipFile zipFile, Filter filter ) throws IOException { Enumeration<? extends ZipEntry> entries = zipFile.entries( ); while ( entries.hasMoreElements( ) ) { ZipEntry srcEntry = entries.nextElement( ); String entryName = srcEntry.getName( ); if ( filter != null && !filter .accept( bundleEntry.getName( ) + "/" + entryName ) ) { log( Level.FINE, "exclude {0}/{1}/{2}", new Object[]{ bundleEntry.getBundleID( ), bundleEntry.getName( ), entryName} ); continue; } if ( entryName.endsWith( "/" ) ) { continue; } if ( existingEntries.contains( entryName ) ) { log( Level.WARNING, "duplicate {0}/{1}/{2}", new Object[]{ bundleEntry.getBundleID( ), bundleEntry.getName( ), entryName} ); continue; } existingEntries.add( entryName ); ZipEntry tgtEntry = new ZipEntry( entryName ); tgtEntry.setTime( srcEntry.getTime( ) ); output.putNextEntry( tgtEntry ); try { InputStream input = zipFile.getInputStream( srcEntry ); try { copyStream( input, output ); } finally { input.close( ); } } finally { output.closeEntry( ); } } }
Example 18
Source File: SiteZipper.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Unzip a zip file into the unzip directory. Only unzips the files that are found within the first folder * contained in the zip archive. * @param zipFilePath Path to ZIP file * @param m_unzipPath Path to directory to unzip file into. * @return The toplevel directory which the zipfile created. * @throws IOException */ public String unzipArchive(String zipFilePath, String m_unzipPath) throws IOException { log.debug("zipFilePath: " + zipFilePath); ZipFile zipFile = new ZipFile(zipFilePath); // Default path from the filename. String unzippedArchivePath = null; Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); //destination file from zip. Straight into the normal archive directory File dest = new File(m_unzipPath, entry.getName()); log.debug("Dest: " + dest.getAbsolutePath()); if(entry.isDirectory()) { //create dir if(!dest.mkdir()) { throw new IOException("Failed to create directory "+ dest); } if (unzippedArchivePath == null) { unzippedArchivePath = entry.getName(); } } else if (unzippedArchivePath != null && entry.getName().startsWith(unzippedArchivePath)){ //extract contents try (InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(dest)) { IOUtils.copy(in, out); } } else { log.info("Ignoring entry: {}", entry.getName()); } } //get original filename, remove timestamp, add -archive log.debug("unzippedArchivePath: " + unzippedArchivePath); return unzippedArchivePath; }
Example 19
Source File: ZipUtils.java From Knowage-Server with GNU Affero General Public License v3.0 | 4 votes |
/** * Unzip skip first level. * * @param zipFile the zip file * @param destDir the dest dir */ public static void unzipSkipFirstLevel(ZipFile zipFile, File destDir) { Enumeration entries = null;; try { entries = zipFile.entries(); } catch (Exception e) { e.printStackTrace(); } try { while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String destFileStr = entry.getName(); destFileStr = (destFileStr.indexOf('/') > 0) ? destFileStr.substring(destFileStr.indexOf('/')) : null; if(destFileStr == null) continue; File destFile = new File(destDir, destFileStr); 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, destFileStr)))); } } zipFile.close(); } catch (IOException ioe) { System.err.println("Unhandled exception:"); ioe.printStackTrace(); return; } }
Example 20
Source File: ZipUtils.java From iMoney with Apache License 2.0 | 2 votes |
/** * 获得压缩文件内压缩文件对象以取得其属性 * * @param zipFile 压缩文件 * @return 返回一个压缩文件列表 * @throws ZipException 压缩文件格式有误时抛出 * @throws IOException IO操作有误时抛出 */ public static Enumeration<?> getEntriesEnumeration(File zipFile) throws ZipException, IOException { ZipFile zf = new ZipFile(zipFile); return zf.entries(); }