Java Code Examples for java.util.zip.ZipInputStream#getNextEntry()
The following examples show how to use
java.util.zip.ZipInputStream#getNextEntry() .
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: AarGeneratorActionTest.java From bazel with Apache License 2.0 | 6 votes |
/** * Runs a {@link FileOperation} on every entry in a zip file. * * @param zip {@link Path} of the zip file to traverse. * @param operation {@link FileOperation} to be run on every entry of the zip file. * @throws IOException if there is an error reading the zip file. */ private void traverseZipFile(Path zip, FileOperation operation) throws IOException { ZipInputStream zis = new ZipInputStream(Files.newInputStream(zip)); ZipEntry z = zis.getNextEntry(); while (z != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; for (int count = 0; count != -1; count = zis.read(buffer)) { baos.write(buffer); } // Replace Windows path separators so that test cases are consistent across platforms. String name = z.getName().replace('\\', '/'); operation.perform( name, z.getTime(), new String(baos.toByteArray(), StandardCharsets.UTF_8)); z = zis.getNextEntry(); } }
Example 2
Source File: DockerComposeYamlInstallationProviderTest.java From keycloak with Apache License 2.0 | 6 votes |
public void shouldWriteCertDirectoryInZip(ZipInputStream zipInput) throws Exception { ZipEntry zipEntry; boolean certsDirFound = false; while ((zipEntry = zipInput.getNextEntry()) != null) { try { if (zipEntry.getName().equals(ROOT_DIR + "certs/")) { certsDirFound = true; assertThat("Zip entry for cert directory is not the correct type", zipEntry.isDirectory(), equalTo(true)); } } finally { zipInput.closeEntry(); } } assertThat("Could not find cert directory", certsDirFound, equalTo(true)); }
Example 3
Source File: AppDeploymentBuilderImpl.java From flowable-engine with Apache License 2.0 | 6 votes |
@Override public AppDeploymentBuilder addZipInputStream(ZipInputStream zipInputStream) { try { ZipEntry entry = zipInputStream.getNextEntry(); while (entry != null) { if (!entry.isDirectory()) { String entryName = entry.getName(); byte[] bytes = IoUtil.readInputStream(zipInputStream, entryName); AppResourceEntity resource = resourceEntityManager.create(); resource.setName(entryName); resource.setBytes(bytes); deployment.addResource(resource); } entry = zipInputStream.getNextEntry(); } } catch (Exception e) { throw new FlowableException("problem reading zip input stream", e); } return this; }
Example 4
Source File: ProxyApplication.java From AndroidStudyDemo with GNU General Public License v2.0 | 6 votes |
/** * 从apk包里面获取dex文件内容(byte) * * @return * @throws IOException */ private byte[] readDexFileFromApk() throws IOException { ByteArrayOutputStream dexByteArrayOutputStream = new ByteArrayOutputStream(); ZipInputStream localZipInputStream = new ZipInputStream( new BufferedInputStream(new FileInputStream( this.getApplicationInfo().sourceDir))); while (true) { ZipEntry localZipEntry = localZipInputStream.getNextEntry(); if (localZipEntry == null) { localZipInputStream.close(); break; } if (localZipEntry.getName().equals("classes.dex")) { byte[] arrayOfByte = new byte[1024]; while (true) { int i = localZipInputStream.read(arrayOfByte); if (i == -1) break; dexByteArrayOutputStream.write(arrayOfByte, 0, i); } } localZipInputStream.closeEntry(); } localZipInputStream.close(); return dexByteArrayOutputStream.toByteArray(); }
Example 5
Source File: CapabilityStatementUtilities.java From org.hl7.fhir.core with Apache License 2.0 | 6 votes |
/** * Extracts a zip file specified by the zipFilePath to a directory specified by * destDirectory (will be created if does not exists) * @param zipFilePath * @param destDirectory * @throws IOException */ public void unzip(String zipFilePath, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); // iterates over entries in the zip file while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { // if the entry is a file, extracts it extractFile(zipIn, filePath); } else { // if the entry is a directory, make the directory File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); }
Example 6
Source File: ZipUtils.java From memetastic with GNU General Public License v3.0 | 6 votes |
private static long getZipLength(final File zipFile) { int count; long totalSize = 0; byte[] buffer = new byte[BUFFER_SIZE]; try { final ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile))); ZipEntry ze; while ((ze = in.getNextEntry()) != null) { if (!ze.isDirectory()) { if (ze.getSize() == -1) { while ((count = in.read(buffer)) != -1) totalSize += count; } else { totalSize += ze.getSize(); } } } in.close(); return totalSize; } catch (IOException ignored) { return -1; } }
Example 7
Source File: RepoGen.java From birt with Eclipse Public License 1.0 | 6 votes |
private Manifest getManifest(final File file) throws IOException { final ZipInputStream zis = new ZipInputStream(new FileInputStream(file)); try { ZipEntry entry = zis.getNextEntry(); while (entry != null) { // read the manifest to determine the name and version number // System.out.println(entry.getName() + " " + entry.isDirectory()); if ("META-INF/MANIFEST.MF".equals(entry.getName())) return new Manifest(zis); entry = zis.getNextEntry(); } } finally { zis.close(); } return null; }
Example 8
Source File: ZipInputStreamTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testAvailable() throws Exception { // NOTE: We don't care about the contents of any of these entries as long as they're // not empty. ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream( zip(new String[] { "foo", "bar", "baz" }, new byte[] { 0, 0, 0, 1, 1, 1 }))); assertEquals(1, zis.available()); zis.getNextEntry(); assertEquals(1, zis.available()); zis.closeEntry(); // On Android M and below, this call would return "1". That seems a bit odd given that the // contract for available states that we should return 1 if there are any bytes left to read // from the "current" entry. assertEquals(0, zis.available()); // There shouldn't be any bytes left to read if the entry is fully consumed... zis.getNextEntry(); Streams.readFullyNoClose(zis); assertEquals(0, zis.available()); // ... or if the entry is fully skipped over. zis.getNextEntry(); zis.skip(Long.MAX_VALUE); assertEquals(0, zis.available()); // There are no entries left in the file, so there whould be nothing left to read. assertNull(zis.getNextEntry()); assertEquals(0, zis.available()); zis.close(); }
Example 9
Source File: KOfficeParser.java From document-management-software with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void internalParse(InputStream input, String filename, String encoding, Locale locale, String tenant, StringBuffer content) { try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/validation", false); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); ZipInputStream zis = new ZipInputStream(input); ZipEntry ze = zis.getNextEntry(); while (ze != null && !ze.getName().equals("maindoc.xml")) { ze = zis.getNextEntry(); } KOfficeContentHandler contentHandler = new KOfficeContentHandler(); xmlReader.setContentHandler(contentHandler); try { xmlReader.parse(new InputSource(zis)); } finally { zis.close(); } content.append(StringUtil.writeToString(new StringReader(contentHandler.getContent()))); } catch (Exception e) { log.warn("Failed to extract KOffice text content", e); } }
Example 10
Source File: AbstractZipFileTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testInflatingStreamsRequiringZipRefill() throws IOException { int originalSize = 1024 * 1024; byte[] readBuffer = new byte[8192]; final File f = createTemporaryZipFile(); writeEntries(createZipOutputStream(f), 1, originalSize, false /* setEntrySize */); ZipInputStream in = new ZipInputStream(new FileInputStream(f)); while (in.getNextEntry() != null) { while (in.read(readBuffer, 0, readBuffer.length) != -1) {} } in.close(); }
Example 11
Source File: ZipUtil.java From xnx3 with Apache License 2.0 | 5 votes |
private static void unzip(ZipInputStream zis, String basePath) throws IOException { ZipEntry entry = zis.getNextEntry(); if (entry != null) { // File file = new File(basePath + File.separator + entry.getName()); File file = new File(basePath + entry.getName()); if (file.isDirectory()) { // 可能存在空文件夹 if (!file.exists()) file.mkdirs(); unzip(zis, basePath); } else { File parentFile = file.getParentFile(); if (parentFile != null && !parentFile.exists()) parentFile.mkdirs(); FileOutputStream fos = new FileOutputStream(file);// 输出流创建文件时必须保证父路径存在 int len = 0; byte[] buf = new byte[1024]; while ((len = zis.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); fos.close(); zis.closeEntry(); unzip(zis, basePath); } } }
Example 12
Source File: SwingIconsDemoTableModel.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 5 votes |
/** * Reads the icon data from the jar file. * * @param in the input stream. */ private boolean readData(final InputStream in) { try { final ZipInputStream iconJar = new ZipInputStream(in); ZipEntry ze = iconJar.getNextEntry(); while (ze != null) { final String fullName = ze.getName(); if (fullName.endsWith(".gif")) { final String category = getCategory(fullName); final String name = getName(fullName); final Image image = getImage(iconJar); final Long bytes = new Long(ze.getSize()); //logger.debug ("Add Icon: " + name); addIconEntry(name, category, image, bytes); } iconJar.closeEntry(); ze = iconJar.getNextEntry(); } } catch (IOException e) { logger.warn("Unable to load the Icons", e); return false; } return true; }
Example 13
Source File: ZipCompressionInputStream.java From hop with Apache License 2.0 | 5 votes |
@Override public Object nextEntry() throws IOException { ZipInputStream zis = (ZipInputStream) delegate; if ( zis == null ) { throw new IOException( "Not a valid input stream!" ); } return zis.getNextEntry(); }
Example 14
Source File: ClosureJavaScriptCompressor.java From htmlcompressor with Apache License 2.0 | 5 votes |
private List<JSSourceFile> getDefaultExterns() throws IOException { InputStream input = ClosureJavaScriptCompressor.class.getResourceAsStream("/externs.zip"); ZipInputStream zip = new ZipInputStream(input); List<JSSourceFile> externs = Lists.newLinkedList(); for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null;) { LimitInputStream entryStream = new LimitInputStream(zip, entry.getSize()); externs.add(JSSourceFile.fromInputStream(entry.getName(), entryStream)); } return externs; }
Example 15
Source File: Closure_83_CommandLineRunner_t.java From coming with MIT License | 5 votes |
/** * @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; }
Example 16
Source File: IfcStepDeserializer.java From IfcPlugins with GNU Affero General Public License v3.0 | 5 votes |
public IfcModelInterface read(InputStream in, String filename, long fileSize, ByteProgressReporter byteProgressReporter) throws DeserializeException { mode = Mode.HEADER; if (filename != null && (filename.toUpperCase().endsWith(".ZIP") || filename.toUpperCase().endsWith(".IFCZIP"))) { ZipInputStream zipInputStream = new ZipInputStream(in); ZipEntry nextEntry; try { nextEntry = zipInputStream.getNextEntry(); if (nextEntry == null) { throw new DeserializeException(DeserializerErrorCode.IFCZIP_CONTAINS_NO_IFC_FILES, "Zip files must contain exactly one IFC-file, this zip-file looks empty"); } if (nextEntry.getName().toUpperCase().endsWith(".IFC")) { IfcModelInterface model = null; FakeClosingInputStream fakeClosingInputStream = new FakeClosingInputStream(zipInputStream); model = read(fakeClosingInputStream, fileSize, byteProgressReporter); if (model.size() == 0) { throw new DeserializeException(DeserializerErrorCode.IFCZIP_CONTAINS_EMPTY_IFC_MODEL, "Uploaded file does not seem to be a correct IFC file"); } if (zipInputStream.getNextEntry() != null) { zipInputStream.close(); throw new DeserializeException(DeserializerErrorCode.IFCZIP_FILE_CONTAINS_TOO_MANY_FILES, "Zip files may only contain one IFC-file, this zip-file contains more files"); } else { zipInputStream.close(); return model; } } else { throw new DeserializeException(DeserializerErrorCode.IFCZIP_MUST_CONTAIN_EXACTLY_ONE_IFC_FILE, "Zip files must contain exactly one IFC-file, this zip-file seems to have one or more non-IFC files"); } } catch (IOException e) { throw new DeserializeException(e); } } else { return read(in, fileSize, byteProgressReporter); } }
Example 17
Source File: ActionPlugins.java From hawkular-alerts with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private void scan() throws IOException { String[] classpath = System.getProperty("java.class.path").split(":"); for (int i=0; i<classpath.length; i++) { if (classpath[i].contains("hawkular") && classpath[i].endsWith("jar")) { ZipInputStream zip = new ZipInputStream(new FileInputStream(classpath[i])); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { if (!entry.isDirectory() && entry.getName().contains("hawkular") && entry.getName().endsWith(".class")) { String className = entry.getName().replace('/', '.'); // including ".class" className = className.substring(0, className.length() - 6); try { log.debugf("Loading class %s", className); Class clazz = cl.loadClass(className); if (clazz.isAnnotationPresent(Plugin.class)) { Plugin plugin = (Plugin)clazz.getAnnotation(Plugin.class); String name = plugin.name(); Object newInstance = clazz.newInstance(); log.infof("Scanning %s", clazz.getName()); if (newInstance instanceof ActionPluginListener) { ActionPluginListener pluginInstance = (ActionPluginListener)newInstance; injectActionPluginSender(name, pluginInstance); plugins.put(name, pluginInstance); } else { throw new IllegalStateException("Plugin [" + name + "] is not instance of " + "ActionPluginListener"); } } } catch (Exception e) { log.errorf("Error loading ActionPlugin %s. Reason: %s", className, e.toString()); System.exit(1); } } } } } }
Example 18
Source File: S3EventProcessorUnzip.java From aws-lambda-unzip with Apache License 2.0 | 4 votes |
@Override public String handleRequest(S3Event s3Event, Context context) { byte[] buffer = new byte[1024]; try { for (S3EventNotificationRecord record: s3Event.getRecords()) { String srcBucket = record.getS3().getBucket().getName(); // Object key may have spaces or unicode non-ASCII characters. String srcKey = record.getS3().getObject().getKey() .replace('+', ' '); srcKey = URLDecoder.decode(srcKey, "UTF-8"); // Detect file type Matcher matcher = Pattern.compile(".*\\.([^\\.]*)").matcher(srcKey); if (!matcher.matches()) { System.out.println("Unable to detect file type for key " + srcKey); return ""; } String extension = matcher.group(1).toLowerCase(); if (!"zip".equals(extension)) { System.out.println("Skipping non-zip file " + srcKey + " with extension " + extension); return ""; } System.out.println("Extracting zip file " + srcBucket + "/" + srcKey); // Download the zip from S3 into a stream AmazonS3 s3Client = new AmazonS3Client(); S3Object s3Object = s3Client.getObject(new GetObjectRequest(srcBucket, srcKey)); ZipInputStream zis = new ZipInputStream(s3Object.getObjectContent()); ZipEntry entry = zis.getNextEntry(); while(entry != null) { String fileName = entry.getName(); String mimeType = FileMimeType.fromExtension(FilenameUtils.getExtension(fileName)).mimeType(); System.out.println("Extracting " + fileName + ", compressed: " + entry.getCompressedSize() + " bytes, extracted: " + entry.getSize() + " bytes, mimetype: " + mimeType); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int len; while ((len = zis.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } InputStream is = new ByteArrayInputStream(outputStream.toByteArray()); ObjectMetadata meta = new ObjectMetadata(); meta.setContentLength(outputStream.size()); meta.setContentType(mimeType); s3Client.putObject(srcBucket, FilenameUtils.getFullPath(srcKey) + fileName, is, meta); is.close(); outputStream.close(); entry = zis.getNextEntry(); } zis.closeEntry(); zis.close(); //delete zip file when done System.out.println("Deleting zip file " + srcBucket + "/" + srcKey + "..."); s3Client.deleteObject(new DeleteObjectRequest(srcBucket, srcKey)); System.out.println("Done deleting"); } return "Ok"; } catch (IOException e) { throw new RuntimeException(e); } }
Example 19
Source File: FileUtils.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 4 votes |
/** * Creates a list of names of matching entries. * @param parentStream * @param pattern * * @return resolved anchors * @throws IOException */ public static List<String> getMatchingZipEntries(InputStream parentStream, String pattern) throws IOException { if (pattern == null) { pattern = ""; } pattern = URLDecoder.decode(pattern, UTF8); // CL-2579 List<String> resolvedAnchors = new ArrayList<String>(); Matcher matcher; Pattern WILDCARD_PATTERN = null; boolean containsWildcard = pattern.contains("?") || pattern.contains("*"); if (containsWildcard) { WILDCARD_PATTERN = Pattern.compile(pattern.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*")); } //resolve url format for zip files ZipInputStream zis = ArchiveUtils.getZipInputStream(parentStream); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { continue; // CLS-537: skip directories, we want to read the first file } // wild cards if (containsWildcard) { matcher = WILDCARD_PATTERN.matcher(entry.getName()); if (matcher.matches()) { resolvedAnchors.add(entry.getName()); } // without wild cards } else if (pattern.isEmpty() || entry.getName().equals(pattern)) { //url is given without anchor; first entry in zip file is used resolvedAnchors.add(pattern); } } // if no wild carded entry found, it is ok if (!pattern.isEmpty() && !containsWildcard && resolvedAnchors.isEmpty()) { throw new IOException("Wrong anchor (" + pattern + ") to zip file."); } return resolvedAnchors; }
Example 20
Source File: FileHelper.java From XMVP with Apache License 2.0 | 4 votes |
/** * 解压 * * @param directory * @param ism * @throws Exception */ public void unzipModuleData(final File directory, InputStream ism) throws Exception { InputStream is = new BufferedInputStream(ism); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); try { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String entryName = entry.getName(); if (!entryName.isEmpty()) { if (entry.isDirectory()) { File file = new File(directory, entryName); if (file.exists()) continue; if (!file.mkdir()) { throw new RuntimeException("Failed to create directory"); } } else { int count; byte[] buff = new byte[BUFFER_SIZE]; BufferedOutputStream dest = null; try { OutputStream fos = new FileOutputStream(new File(directory, entryName)); dest = new BufferedOutputStream(fos, BUFFER_SIZE); while ((count = zis.read(buff, 0, BUFFER_SIZE)) != -1) { dest.write(buff, 0, count); } dest.flush(); } finally { if (dest != null) { dest.close(); } } } } } } catch (Exception e) { e.printStackTrace(); } finally { is.close(); zis.close(); } }