类java.util.zip.ZipInputStream源码实例Demo

下面列出了怎么用java.util.zip.ZipInputStream的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Tomcat8-Source-Read   文件: SignCode.java
/**
 * Removes base64 encoding, unzips the files and writes the new files over
 * the top of the old ones.
 */
private static void extractFilesFromApplicationString(String data, List<File> files)
        throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(data));
    try (ZipInputStream zis = new ZipInputStream(bais)) {
        byte[] buf = new byte[32 * 1024];
        for (int i = 0; i < files.size(); i ++) {
            try (FileOutputStream fos = new FileOutputStream(files.get(i))) {
                zis.getNextEntry();
                int numRead;
                while ( (numRead = zis.read(buf)) >= 0) {
                    fos.write(buf, 0 , numRead);
                }
            }
        }
    }
}
 
源代码2 项目: panda   文件: ZipUtilsTest.java
@Test
void extract() throws IOException {
    File outputDirectory = directoryPath.toFile();

    BufferedInputStream stream = new BufferedInputStream(ZipUtils.class.getResourceAsStream("/commons/zip-utils-test.zip"));
    ZipInputStream zipStream = new ZipInputStream(stream);
    ZipUtils.extract(zipStream, outputDirectory);

    File directory = new File(outputDirectory, "directory");
    Assertions.assertTrue(directory.exists());

    Node<File> map = FileUtils.collectFiles(directory);
    Assertions.assertEquals("directory", map.getElement().getName());

    Set<String> files = map.collectLeafs(File::isFile).stream()
            .map(File::getName)
            .collect(Collectors.toSet());
    Assertions.assertEquals(Sets.newHashSet("1.txt", "2.txt"), files);
}
 
源代码3 项目: Box   文件: ClsSet.java
private void load(File input) throws IOException, DecodeException {
	String name = input.getName();
	try (InputStream inputStream = new FileInputStream(input)) {
		if (name.endsWith(CLST_EXTENSION)) {
			load(inputStream);
		} else if (name.endsWith(".jar")) {
			try (ZipInputStream in = new ZipInputStream(inputStream)) {
				ZipEntry entry = in.getNextEntry();
				while (entry != null) {
					if (entry.getName().endsWith(CLST_EXTENSION) && ZipSecurity.isValidZipEntry(entry)) {
						load(in);
					}
					entry = in.getNextEntry();
				}
			}
		} else {
			throw new JadxRuntimeException("Unknown file format: " + name);
		}
	}
}
 
源代码4 项目: netbeans   文件: CheckoutTest.java
private void unpack (String filename) throws IOException {
    File zipLarge = new File(getDataDir(), filename);
    ZipInputStream is = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipLarge)));
    ZipEntry entry;
    while ((entry = is.getNextEntry()) != null) {
        File unpacked = new File(workDir, entry.getName());
        FileChannel channel = new FileOutputStream(unpacked).getChannel();
        byte[] bytes = new byte[2048];
        try {
            int len;
            long size = entry.getSize();
            while (size > 0 && (len = is.read(bytes, 0, 2048)) > 0) {
                ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, len);
                int j = channel.write(buffer);
                size -= len;
            }
        } finally {
            channel.close();
        }
    }
    ZipEntry e = is.getNextEntry();
}
 
源代码5 项目: gocd   文件: ArtifactsServiceTest.java
@Test
void shouldLogErrorIfFailedToSaveFileWhenAttemptHitsMaxAttempts() throws IOException {
    final File logsDir = new File("logs");
    final ByteArrayInputStream stream = new ByteArrayInputStream("".getBytes());
    String buildInstanceId = "1";
    final File destFile = new File(logsDir,
            buildInstanceId + File.separator + "generated" + File.separator + LOG_XML_NAME);
    final IOException ioException = new IOException();

    Mockito.doThrow(ioException).when(zipUtil).unzip(any(ZipInputStream.class), any(File.class));

    try (LogFixture logFixture = logFixtureFor(ArtifactsService.class, Level.DEBUG)) {
        ArtifactsService artifactsService = new ArtifactsService(resolverService, stageService, artifactsDirHolder, zipUtil);
        artifactsService.saveFile(destFile, stream, true, PUBLISH_MAX_RETRIES);
        String result;
        synchronized (logFixture) {
            result = logFixture.getLog();
        }
        assertThat(result).contains("Failed to save the file to:");
    }
}
 
源代码6 项目: dss   文件: ASiCUtils.java
/**
 * Returns the next entry from the given ZipInputStream by skipping corrupted or
 * not accessible files NOTE: returns null only when the end of ZipInputStream
 * is reached
 * 
 * @param zis {@link ZipInputStream} to get next entry from
 * @return list of file name {@link String}s
 * @throws DSSException if too much tries failed
 */
public static ZipEntry getNextValidEntry(ZipInputStream zis) {
	int counter = 0;
	while (counter < MAX_MALFORMED_FILES) {
		try {
			return zis.getNextEntry();
		} catch (Exception e) {
			LOG.warn("ZIP container contains a malformed, corrupted or not accessible entry! The entry is skipped. Reason: [{}]", e.getMessage());
			// skip the entry and continue until find the next valid entry or end of the
			// stream
			counter++;
			closeEntry(zis);
		}
	}
	throw new DSSException("Unable to retrieve a valid ZipEntry (" + MAX_MALFORMED_FILES + " tries)");
}
 
源代码7 项目: nifi   文件: ZipUnpackerSequenceFileWriter.java
@Override
protected void processInputStream(InputStream stream, final FlowFile flowFile, final Writer writer) throws IOException {

    try (final ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(stream))) {
        ZipEntry zipEntry;
        while ((zipEntry = zipIn.getNextEntry()) != null) {
            if (zipEntry.isDirectory()) {
                continue;
            }
            final File file = new File(zipEntry.getName());
            final String key = file.getName();
            long fileSize = zipEntry.getSize();
            final InputStreamWritable inStreamWritable = new InputStreamWritable(zipIn, (int) fileSize);
            writer.append(new Text(key), inStreamWritable);
            logger.debug("Appending FlowFile {} to Sequence File", new Object[]{key});
        }
    }
}
 
源代码8 项目: joyqueue   文件: Zip.java
@Override
public void decompress(final byte[] buf, final int offset, final int size, final OutputStream out) throws
        IOException {
    if (buf == null || buf.length == 0 || size <= 0 || offset >= buf.length || out == null) {
        return;
    }
    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(buf, offset, size));
    try {
        zis.getNextEntry();
        byte[] buffer = new byte[1024];
        int position = -1;
        while ((position = zis.read(buffer)) != -1) {
            out.write(buffer, 0, position);
        }
    } finally {
        zis.close();
    }
}
 
源代码9 项目: shrinker   文件: JarProcessor.java
private List<Pair<String, byte[]>> readZipEntries(Path src) throws IOException {
    ImmutableList.Builder<Pair<String, byte[]>> list = ImmutableList.builder();
    try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(Files.readAllBytes(src)))) {
        for (ZipEntry entry = zip.getNextEntry();
             entry != null;
             entry = zip.getNextEntry()) {
            String name = entry.getName();
            if (!name.endsWith(".class")) {
                // skip
                continue;
            }
            long entrySize = entry.getSize();
            if (entrySize >= Integer.MAX_VALUE) {
                throw new OutOfMemoryError("Too large class file " + name + ", size is " + entrySize);
            }
            byte[] bytes = readByteArray(zip, (int) entrySize);
            list.add(Pair.of(name, bytes));
        }
    }
    return list.build();
}
 
源代码10 项目: Flashtool   文件: OS.java
public static void ZipExplodeTo(InputStream stream, File outfolder) throws FileNotFoundException, IOException  {
	byte buffer[] = new byte[10240];
	outfolder.mkdirs();
	ZipInputStream zis = new ZipInputStream(stream);
	ZipEntry ze = zis.getNextEntry();
	while (ze != null) {
		FileOutputStream fout = new FileOutputStream(outfolder.getAbsolutePath()+File.separator+ze.getName());
		int len;
		while ((len=zis.read(buffer))>0) {
			fout.write(buffer,0,len);
		}
		fout.close();
		ze=zis.getNextEntry();
	}
	zis.closeEntry();
	zis.close();
	stream.close();
}
 
/**
 * 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();
}
 
源代码12 项目: TVRemoteIME   文件: FileHelper.java
/*************ZIP file operation***************/
public static boolean readZipFile(String zipFileName, StringBuffer crc) {
	try {
		ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
		ZipEntry entry;
		while ((entry = zis.getNextEntry()) != null) {
			long size = entry.getSize();
			crc.append(entry.getCrc() + ", size: " + size);
        }
        zis.close();
	} catch (Exception ex) {
		Log.i(TAG,"Exception: " + ex.toString());
		return false;
	}
	return true;
}
 
源代码13 项目: FoxBPM   文件: DeploymentCollectionResource.java
@Post
public String deploy(Representation entity){
	InputStream input = null;
	String processDefinitionKey = null;
	try {
		input = entity.getStream();
		if(input == null){
			throw new FoxbpmPluginException("请求中必须包含文件流", "Rest服务");
		}
		ModelService modelService = FoxBpmUtil.getProcessEngine().getModelService();
		ZipInputStream zip = new ZipInputStream(input);
		DeploymentBuilder deploymentBuilder = modelService.createDeployment();
		deploymentBuilder.addZipInputStream(zip);
		Deployment deployment = deploymentBuilder.deploy();
		setStatus(Status.SUCCESS_CREATED);
		ProcessDefinitionQuery processDefinitionQuery = modelService.createProcessDefinitionQuery();
		processDefinitionKey = processDefinitionQuery.deploymentId(deployment.getId()).singleResult().getId();
	} catch (Exception e) {
		if (e instanceof FoxBPMException) {
			throw (FoxBPMException) e;
		}
		throw new FoxBPMException(e.getMessage(), e);
	}		
	return processDefinitionKey;
}
 
@Override
public BeanArchiveBuilder handle(String beanArchiveReference) {

    // An external form of a wildfly beans.xml URL will be something like:
    // vfs:/content/_DEFAULT___DEFAULT__1f4a3572-fc97-41f5-8fed-0e7e7f7895df.war/WEB-INF/lib/4e0a1b50-4a74-429d-b519-9eedcac11046.jar/META-INF/beans.xml
    beanArchiveReference = beanArchiveReference.substring(0, beanArchiveReference.lastIndexOf("/META-INF/beans.xml"));

    if (beanArchiveReference.endsWith(".war")) {
        // We only use this handler for libraries - WEB-INF classes are handled by ServletContextBeanArchiveHandler
        return null;
    }

    try {
        URL url = new URL(beanArchiveReference);
        try (ZipInputStream in = openStream(url)) {
            BeanArchiveBuilder builder = new BeanArchiveBuilder();
            handleLibrary(url, in, builder);
            return builder;
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
@Test
public void convertAndReconcileStatedRelationshipsToOwlRefset() throws IOException, OWLOntologyCreationException, ConversionException {
	File baseRf2SnapshoZip = ZipUtil.zipDirectoryRemovingCommentsAndBlankLines("src/test/resources/SnomedCT_MiniRF2_Base_snapshot");
	File midCycleDeltaZip = ZipUtil.zipDirectoryRemovingCommentsAndBlankLines("src/test/resources/SnomedCT_MiniRF2_MidAuthoringCycle_delta");
	File compleOwlSnapshotZip = ZipUtil.zipDirectoryRemovingCommentsAndBlankLines("src/test/resources/SnomedCT_MiniRF2_Base_CompleteOwl_snapshot");

	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	service.convertStatedRelationshipsToOwlReRefsetAndReconcileWithPublishedArchive(new FileInputStream(baseRf2SnapshoZip), new FileInputStream(midCycleDeltaZip), new FileInputStream(compleOwlSnapshotZip), byteArrayOutputStream, "20190731");

	String owlRefset;
	try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()))) {
		ZipEntry nextEntry = zipInputStream.getNextEntry();
		assertEquals("sct2_sRefset_OWLAxiomDelta_INT_20190731.txt", nextEntry.getName());
		owlRefset = StreamUtils.copyToString(zipInputStream, Charset.forName("UTF-8"));
	}

	assertFalse("Output should not contain the snomed axiom prefix", owlRefset.contains("<http://snomed.info/id/"));
	assertEquals(
			"id\teffectiveTime\tactive\tmoduleId\trefsetId\treferencedComponentId\towlExpression\n" +
			"e35258b4-15d8-4fb2-bea5-dcc6b5e7de62\t\t1\t900000000000207008\t733073007\t8801005\tSubClassOf(ObjectIntersectionOf(:73211009 ObjectSomeValuesFrom(:roleGroup ObjectSomeValuesFrom(:100106001 :100102001))) :8801005)\n" +
			"1\t\t1\t900000000000207008\t733073007\t8801005\tSubClassOf(:8801005 :73211009)\n" +
			"2\t\t1\t900000000000207008\t733073007\t73211009\tSubClassOf(:73211009 :362969004)\n" +
			"2b75cd59-24c6-46e4-8565-0ab3da7f0ab3\t\t0\t900000000000207008\t733073007\t362969004\tEquivalentClasses(:362969004 ObjectIntersectionOf(:404684003 ObjectSomeValuesFrom(:609096000 ObjectSomeValuesFrom(:363698007 :113331007))))\n",
			owlRefset);
}
 
源代码16 项目: development   文件: FilesTest.java
protected Map<String, byte[]> getZipEntries(byte[] content)
        throws IOException {
    Map<String, byte[]> result = new HashMap<String, byte[]>();
    ZipInputStream in = new ZipInputStream(
            new ByteArrayInputStream(content));
    ZipEntry entry;
    while ((entry = in.getNextEntry()) != null) {
        String path = entry.getName();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int b;
        while ((b = in.read()) != -1)
            buffer.write(b);
        assertNull("duplicate entry " + path, result.put(path, buffer
                .toByteArray()));
    }
    return result;
}
 
源代码17 项目: birt   文件: RepoGen.java
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;
}
 
源代码18 项目: MikuMikuStudio   文件: BasicGameWizardIterator.java
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());
                if ("nbproject/project.xml".equals(entry.getName())) {
                    // Special handling for setting name of Ant-based projects; customize as needed:
                    filterProjectXML(fo, str, projectRoot.getName());
                } else {
                    writeFile(str, fo);
                }
            }
        }
    } finally {
        source.close();
    }
}
 
源代码19 项目: triplea   文件: AvailableGames.java
private static Map<String, URI> getGamesFromZip(final File map) {
  final Map<String, URI> availableGames = new HashMap<>();

  try (InputStream fis = new FileInputStream(map);
      ZipInputStream zis = new ZipInputStream(fis);
      URLClassLoader loader = new URLClassLoader(new URL[] {map.toURI().toURL()})) {
    ZipEntry entry = zis.getNextEntry();
    while (entry != null) {
      if (entry.getName().contains("games/") && entry.getName().toLowerCase().endsWith(".xml")) {
        final URL url = loader.getResource(entry.getName());
        if (url != null) {
          availableGames.putAll(
              getAvailableGames(URI.create(url.toString().replace(" ", "%20"))));
        }
      }
      // we have to close the loader to allow files to be deleted on windows
      zis.closeEntry();
      entry = zis.getNextEntry();
    }
  } catch (final IOException e) {
    log.log(Level.SEVERE, "Error reading zip file in: " + map.getAbsolutePath(), e);
  }
  return availableGames;
}
 
private 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());
                writeFile(str, fo);
            }
        }
    } finally {
        source.close();
    }
}
 
@Override
public BeanArchiveBuilder handle(String beanArchiveReference) {

    // An external form of a wildfly beans.xml URL will be something like:
    // vfs:/content/_DEFAULT___DEFAULT__1f4a3572-fc97-41f5-8fed-0e7e7f7895df.war/WEB-INF/lib/4e0a1b50-4a74-429d-b519-9eedcac11046.jar/META-INF/beans.xml
    beanArchiveReference = beanArchiveReference.substring(0, beanArchiveReference.lastIndexOf("/META-INF/beans.xml"));

    if (beanArchiveReference.endsWith(".war")) {
        // We only use this handler for libraries - WEB-INF classes are handled by ServletContextBeanArchiveHandler
        return null;
    }

    try {
        URL url = new URL(beanArchiveReference);
        try (ZipInputStream in = openStream(url)) {
            BeanArchiveBuilder builder = new BeanArchiveBuilder();
            handleLibrary(url, in, builder);
            return builder;
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
源代码22 项目: Flashtool   文件: OS.java
public static void ZipExplodeToHere(String zippath) throws FileNotFoundException, IOException  {
	byte buffer[] = new byte[10240];
	File zipfile = new File(zippath);
	File outfolder = new File(zipfile.getParentFile().getAbsolutePath());
	outfolder.mkdirs();
	ZipInputStream zis = new ZipInputStream(new FileInputStream(zippath));
	ZipEntry ze = zis.getNextEntry();
	while (ze != null) {
		FileOutputStream fout = new FileOutputStream(outfolder.getAbsolutePath()+File.separator+ze.getName());
		int len;
		while ((len=zis.read(buffer))>0) {
			fout.write(buffer,0,len);
		}
		fout.close();
		ze=zis.getNextEntry();
	}
	zis.closeEntry();
	zis.close();
}
 
@Test
void generateDita(@TempDir final File temporaryFolder, final TestInfo info) throws IOException {
    final File output = new File(temporaryFolder, info.getTestMethod().get().getName() + ".zip");
    new DitaDocumentationGenerator(
            new File[] {
                    copyBinaries("org.talend.test.valid", temporaryFolder, info.getTestMethod().get().getName()) },
            Locale.ROOT, log, output, true, true).run();
    assertTrue(output.exists());
    final Map<String, String> files = new HashMap<>();
    try (final ZipInputStream zip = new ZipInputStream(new FileInputStream(output))) {
        ZipEntry nextEntry;
        while ((nextEntry = zip.getNextEntry()) != null) {
            files.put(nextEntry.getName(), IO.slurp(zip));
        }
    }
    try (final BufferedReader reader = resource("generateDita1.xml")) {
        assertEquals(reader.lines().collect(joining("\n")), files.get("generateDita/test/my.dita").trim());
    }
    try (final BufferedReader reader = resource("generateDita2.xml")) {
        assertEquals(reader.lines().collect(joining("\n")), files.get("generateDita/test/my2.dita").trim());
    }
    assertEquals(4, files.size());
    // folders
    assertEquals("", files.get("generateDita/test/"));
    assertEquals("", files.get("generateDita/"));
}
 
@Test
public void testDeployResources_NoParent() {

    final Resource[] resources = new Resource[] { resourceMock1, resourceMock2, resourceMock3 };
    classUnderTest.deployResources(deploymentNameHint, resources, repositoryServiceMock);

    when(fileMock1.getParentFile()).thenReturn(null);
    when(fileMock2.getParentFile()).thenReturn(parentFile2Mock);
    when(parentFile2Mock.isDirectory()).thenReturn(false);
    when(fileMock3.getParentFile()).thenReturn(null);

    verify(repositoryServiceMock, times(3)).createDeployment();
    verify(deploymentBuilderMock, times(3)).enableDuplicateFiltering();
    verify(deploymentBuilderMock, times(1)).name(deploymentNameHint + "." + resourceName1);
    verify(deploymentBuilderMock, times(1)).name(deploymentNameHint + "." + resourceName2);
    verify(deploymentBuilderMock, times(1)).name(deploymentNameHint + "." + resourceName3);
    verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName1), isA(InputStream.class));
    verify(deploymentBuilderMock, times(1)).addInputStream(eq(resourceName2), isA(InputStream.class));
    verify(deploymentBuilderMock, times(1)).addZipInputStream(isA(ZipInputStream.class));
    verify(deploymentBuilderMock, times(3)).deploy();
}
 
public DeploymentBuilder addZipInputStream(ZipInputStream zipInputStream) {
  try {
    ZipEntry entry = zipInputStream.getNextEntry();
    while (entry != null) {
      if (!entry.isDirectory()) {
        String entryName = entry.getName();
        addInputStream(entryName, zipInputStream);
      }
      entry = zipInputStream.getNextEntry();
    }
  } catch (Exception e) {
    throw new ProcessEngineException("problem reading zip input stream", e);
  }
  return this;
}
 
源代码26 项目: nifi   文件: TestMergeContent.java
@Test
public void testZip() throws IOException {
    final TestRunner runner = TestRunners.newTestRunner(new MergeContent());
    runner.setProperty(MergeContent.MAX_BIN_AGE, "1 sec");
    runner.setProperty(MergeContent.MERGE_FORMAT, MergeContent.MERGE_FORMAT_ZIP);

    createFlowFiles(runner);
    runner.run();

    runner.assertQueueEmpty();
    runner.assertTransferCount(MergeContent.REL_MERGED, 1);
    runner.assertTransferCount(MergeContent.REL_FAILURE, 0);
    runner.assertTransferCount(MergeContent.REL_ORIGINAL, 3);

    final MockFlowFile bundle = runner.getFlowFilesForRelationship(MergeContent.REL_MERGED).get(0);
    try (final InputStream rawIn = new ByteArrayInputStream(runner.getContentAsByteArray(bundle)); final ZipInputStream in = new ZipInputStream(rawIn)) {
        Assert.assertNotNull(in.getNextEntry());
        final byte[] part1 = IOUtils.toByteArray(in);
        Assert.assertTrue(Arrays.equals("Hello".getBytes("UTF-8"), part1));

        in.getNextEntry();
        final byte[] part2 = IOUtils.toByteArray(in);
        Assert.assertTrue(Arrays.equals(", ".getBytes("UTF-8"), part2));

        in.getNextEntry();
        final byte[] part3 = IOUtils.toByteArray(in);
        Assert.assertTrue(Arrays.equals("World!".getBytes("UTF-8"), part3));
    }
    bundle.assertAttributeEquals(CoreAttributes.MIME_TYPE.key(), "application/zip");
}
 
源代码27 项目: lottie-android   文件: LottieCompositionFactory.java
/**
 * Parse an animation from src/main/assets. It is recommended to use {@link #fromRawRes(Context, int)} instead.
 * The asset file name will be used as a cache key so future usages won't have to parse the json again.
 * However, if your animation has images, you may package the json and images as a single flattened zip file in assets.
 *
 * Pass null as the cache key to skip the cache.
 *
 * @see #fromZipStreamSync(ZipInputStream, String)
 */
@WorkerThread
public static LottieResult<LottieComposition> fromAssetSync(Context context, String fileName, @Nullable String cacheKey) {
  try {
    if (fileName.endsWith(".zip")) {
      return fromZipStreamSync(new ZipInputStream(context.getAssets().open(fileName)), cacheKey);
    }
    return fromJsonInputStreamSync(context.getAssets().open(fileName), cacheKey);
  } catch (IOException e) {
    return new LottieResult<>(e);
  }
}
 
源代码28 项目: openjdk-8-source   文件: Constructor.java
public static void main(String[] args) throws Exception {
    try {
        ZipInputStream in = new ZipInputStream(null);
        throw new Exception("Constructor did not check the null argument");
    } catch (NullPointerException e) {
    }
}
 
源代码29 项目: j2objc   文件: ZipInputStreamTest.java
/**
 * java.util.zip.ZipInputStream#skip(long)
 */
public void test_skipJ() throws Exception {
    zentry = zis.getNextEntry();
    byte[] rbuf = new byte[(int) zentry.getSize()];
    zis.skip(2);
    int r = zis.read(rbuf, 0, rbuf.length);
    assertEquals("Failed to skip data", 10, r);

    zentry = zis.getNextEntry();
    zentry = zis.getNextEntry();
    long s = zis.skip(1025);
    assertEquals("invalid skip: " + s, 1025, s);

    try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes))) {
        zis.getNextEntry();
        long skipLen = dataBytes.length / 2;
        assertEquals("Assert 0: failed valid skip", skipLen, zis.skip(skipLen));
        zis.skip(dataBytes.length);
        assertEquals("Assert 1: performed invalid skip", 0, zis.skip(1));
        assertEquals("Assert 2: failed zero len skip", 0, zis.skip(0));
        try {
            zis.skip(-1);
            fail("Assert 3: Expected Illegal argument exception");
        } catch (IllegalArgumentException e) {
            // Expected
        }
    }
}
 
源代码30 项目: awacs   文件: Processor.java
private void processEntry(final ZipInputStream zis, final ZipEntry ze,
        final ContentHandlerFactory handlerFactory) {
    ContentHandler handler = handlerFactory.createContentHandler();
    try {

        // if (CODE2ASM.equals(command)) { // read bytecode and process it
        // // with TraceClassVisitor
        // ClassReader cr = new ClassReader(readEntry(zis, ze));
        // cr.accept(new TraceClassVisitor(null, new PrintWriter(os)),
        // false);
        // }

        boolean singleInputDocument = inRepresentation == SINGLE_XML;
        if (inRepresentation == BYTECODE) { // read bytecode and process it
            // with handler
            ClassReader cr = new ClassReader(readEntry(zis, ze));
            cr.accept(new SAXClassAdapter(handler, singleInputDocument), 0);

        } else { // read XML and process it with handler
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(handler);
            reader.parse(new InputSource(
                    singleInputDocument ? (InputStream) new ProtectedInputStream(
                            zis) : new ByteArrayInputStream(readEntry(zis,
                            ze))));

        }
    } catch (Exception ex) {
        update(ze.getName(), 0);
        update(ex, 0);
    }
}
 
 类所在包
 同包方法