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

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

源代码1 项目: capsule-maven-plugin   文件: Mojo.java
String addDirectoryToJar(final JarOutputStream jar, final String outputDirectory) throws IOException {

		// format the output directory
		String formattedOutputDirectory = "";
		if (outputDirectory != null && !outputDirectory.isEmpty()) {
			if (!outputDirectory.endsWith("/")) {
				formattedOutputDirectory = outputDirectory + File.separatorChar;
			} else {
				formattedOutputDirectory = outputDirectory;
			}
		}

		if (!formattedOutputDirectory.isEmpty()) {
			try {
				jar.putNextEntry(new ZipEntry(formattedOutputDirectory));
				jar.closeEntry();
			} catch (final ZipException ignore) {} // ignore duplicate entries and other errors
		}
		return formattedOutputDirectory;
	}
 
源代码2 项目: jackrabbit-filevault   文件: UpdateableZipFile.java
public ZipEntry getEntry(String name) {
    if (!file.exists()) {
        return null;
    }
    try {
        InputStream in = FileUtils.openInputStream(file);
        ZipInputStream zin = new ZipInputStream(in);
        try {
            ZipEntry entry = zin.getNextEntry();
            while (entry != null) {
                if (entry.getName().equals(name)) {
                    zin.closeEntry();
                    break;
                }
                entry = zin.getNextEntry();
            }
            return entry;
        } finally {
            IOUtils.closeQuietly(zin);
            IOUtils.closeQuietly(in);
        }
    } catch (IOException e) {
        log.error("Error while retrieving zip entry {}: {}", name, e.toString());
        return null;
    }
}
 
源代码3 项目: AndroidUtilCode   文件: ZipUtils.java
/**
 * Return the files' path in ZIP file.
 *
 * @param zipFile The ZIP file.
 * @return the files' path in ZIP file
 * @throws IOException if an I/O error has occurred
 */
public static List<String> getFilesPath(final File zipFile)
        throws IOException {
    if (zipFile == null) return null;
    List<String> paths = new ArrayList<>();
    ZipFile zip = new ZipFile(zipFile);
    Enumeration<?> entries = zip.entries();
    while (entries.hasMoreElements()) {
        String entryName = ((ZipEntry) entries.nextElement()).getName().replace("\\", "/");
        if (entryName.contains("../")) {
            Log.e("ZipUtils", "entryName: " + entryName + " is dangerous!");
            paths.add(entryName);
        } else {
            paths.add(entryName);
        }
    }
    zip.close();
    return paths;
}
 
private static void addToZipFile(String filePath, String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {

		File file = new File(filePath + "/" + fileName);
		FileInputStream fis = new FileInputStream(file);
		ZipEntry zipEntry = new ZipEntry(fileName);
		zos.putNextEntry(zipEntry);

		byte[] bytes = new byte[1024];
		int length;
		while ((length = fis.read(bytes)) >= 0) {
			zos.write(bytes, 0, length);
		}

		zos.closeEntry();
		fis.close();
	}
 
源代码5 项目: sarl   文件: SARLRuntime.java
/** Replies if the given JAR file contains a SRE bootstrap.
 *
 * <p>The SRE bootstrap detection is based on the service definition within META-INF folder.
 *
 * @param jarFile the JAR file to test.
 * @return <code>true</code> if the given directory contains a SRE. Otherwise <code>false</code>.
 * @since 0.7
 * @see #containsUnpackedBootstrap(File)
 */
public static boolean containsPackedBootstrap(File jarFile) {
	try (JarFile jFile = new JarFile(jarFile)) {
		final ZipEntry jEntry = jFile.getEntry(SREManifestPreferenceConstants.SERVICE_SRE_BOOTSTRAP);
		if (jEntry != null) {
			try (InputStream is = jFile.getInputStream(jEntry)) {
				try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
					String line = reader.readLine();
					if (line != null) {
						line = line.trim();
						if (!line.isEmpty()) {
							return true;
						}
					}
				}
			}
		}
	} catch (IOException exception) {
		//
	}
	return false;
}
 
源代码6 项目: buck   文件: ZipOutputStreamTest.java
@Test
public void writingTheSameFileMoreThanOnceWhenInOverwriteModeWritesItOnceToTheZip()
    throws IOException {
  final String name = "example.txt";
  byte[] input1 = "cheese".getBytes(UTF_8);
  byte[] input2 = "cake".getBytes(UTF_8);
  byte[] input3 = "dessert".getBytes(UTF_8);
  try (CustomZipOutputStream out =
      ZipOutputStreams.newOutputStream(output, OVERWRITE_EXISTING)) {
    ZipEntry entry = new ZipEntry(name);
    out.putNextEntry(entry);
    out.write(input1);
    out.putNextEntry(entry);
    out.write(input2);
    out.putNextEntry(entry);
    out.write(input3);
  }

  assertEquals(ImmutableList.of(new NameAndContent(name, input3)), getExtractedEntries(output));
}
 
源代码7 项目: microprofile-starter   文件: ZipFileCreator.java
public byte[] createArchive() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (ZipOutputStream zos = new ZipOutputStream(baos)) {

        for (Map.Entry<String, byte[]> entry : archiveContent.entrySet()) {

            ZipEntry zipEntry = new ZipEntry(entry.getKey());

            zos.putNextEntry(zipEntry);
            zos.write(entry.getValue());
            zos.closeEntry();

        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    archiveContent.clear();
    return baos.toByteArray();
}
 
源代码8 项目: vespa   文件: BundleTest.java
@Test
public void require_that_component_jar_file_contains_compile_artifacts() {
    String depJrt = "dependencies/jrt";
    Pattern jrtPattern = Pattern.compile(depJrt + snapshotOrVersionOrNone);
    ZipEntry jrtEntry = null;

    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        var e = entries.nextElement();
        if (e.getName().startsWith(depJrt)) {
            if (jrtPattern.matcher(e.getName()).matches()) {
                jrtEntry = e;
                break;
            }
        }
    }
    assertNotNull("Component jar file did not contain jrt dependency.", jrtEntry);
}
 
源代码9 项目: NullAway   文件: DefinitelyDerefedParamsDriver.java
/**
 * Write model jar file with nullability model at DEFAULT_ASTUBX_LOCATION
 *
 * @param outPath Path of output model jar file.
 */
private void writeModelJAR(String outPath) throws IOException {
  Preconditions.checkArgument(
      outPath.endsWith(ASTUBX_JAR_SUFFIX), "invalid model file path! " + outPath);
  ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outPath));
  if (!nonnullParams.isEmpty()) {
    ZipEntry entry = new ZipEntry(DEFAULT_ASTUBX_LOCATION);
    // Set the modification/creation time to 0 to ensure that this jars always have the same
    // checksum
    entry.setTime(0);
    entry.setCreationTime(FileTime.fromMillis(0));
    zos.putNextEntry(entry);
    writeModel(new DataOutputStream(zos));
    zos.closeEntry();
  }
  zos.close();
  LOG(VERBOSE, "Info", "wrote model to: " + outPath);
}
 
源代码10 项目: LibScout   文件: ApkUtils.java
public static Set<ZipEntry> getClassesDex(File apkFile) throws ZipException, IOException {
	HashSet<ZipEntry> result = new HashSet<ZipEntry>();
	ZipFile f = new ZipFile(apkFile);
	
    final Enumeration<? extends ZipEntry> entries = f.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        if (entry.getName().matches("classes[1-9]{0,1}\\.dex"))
        	result.add(entry);
    }
    
    // TODO: unzip those entries to tmp dir and return set<Files>

    f.close();
    return result;
}
 
源代码11 项目: zuihou-admin-boot   文件: ZipUtils.java
/**
 * 通过流打包下载文件
 *
 * @param out
 * @param fileName
 * @param
 */
public static void zipFilesByInputStream(ZipOutputStream out, String fileName, InputStream is) throws Exception {
    byte[] buf = new byte[1024];
    try {
        out.putNextEntry(new ZipEntry(fileName));
        int len;
        while ((len = is.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        is.close();
    } catch (Exception e) {
        throw e;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
 
源代码12 项目: native-obfuscator   文件: TestExtraTime.java
static void testTimeConversions(long from, long to, long step) {
    ZipEntry ze = new ZipEntry("TestExtraTime.java");
    for (long time = from; time <= to; time += step) {
        ze.setTime(time);
        FileTime lastModifiedTime = ze.getLastModifiedTime();
        if (lastModifiedTime.toMillis() != time) {
            throw new RuntimeException("setTime should make getLastModifiedTime " +
                    "return the specified instant: " + time +
                    " got: " + lastModifiedTime.toMillis());
        }
        if (ze.getTime() != time) {
            throw new RuntimeException("getTime after setTime, expected: " +
                    time + " got: " + ze.getTime());
        }
    }
}
 
源代码13 项目: nd4j   文件: JarResource.java
/**
 * Returns requested ClassPathResource as InputStream object
 *
 * @return File requested at constructor call
 * @throws FileNotFoundException
 */
public InputStream getInputStream() throws FileNotFoundException {
    URL url = this.getUrl();
    if (isJarURL(url)) {
        try {
            url = extractActualUrl(url);
            ZipFile zipFile = new ZipFile(url.getFile());
            ZipEntry entry = zipFile.getEntry(this.resourceName);

            InputStream stream = zipFile.getInputStream(entry);
            return stream;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        File srcFile = this.getFile();
        return new FileInputStream(srcFile);
    }
}
 
源代码14 项目: tracecompass   文件: TestDirectoryStructureUtil.java
private static void addToArchive(ZipOutputStream zos, File dir, File root) throws IOException {
    byte[] buffer = new byte[1024];
    int length;
    int index = root.getAbsolutePath().length();
    for (File file : dir.listFiles()) {
        String name = file.getAbsolutePath().substring(index);
        if (file.isDirectory()) {
            if (file.listFiles().length != 0) {
                addToArchive(zos, file, root);
            } else {
                zos.putNextEntry(new ZipEntry(name + File.separator));
                zos.closeEntry();
            }
        } else {
            try (FileInputStream fis = new FileInputStream(file)) {
                zos.putNextEntry(new ZipEntry(name));
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
            }
        }
    }
}
 
源代码15 项目: arx   文件: WorkerLoad.java
/**
 * Reads the input from the file.
 *
 * @param config
 * @param zip
 * @throws IOException
 */
private void readInput(final ModelConfiguration config, final ZipFile zip) throws IOException {

    final ZipEntry entry = zip.getEntry("data/input.csv"); //$NON-NLS-1$
    if (entry == null) { return; }
    
    // Read input
    // Use project delimiter for backwards compatibility
    config.setInput(Data.create(new BufferedInputStream(zip.getInputStream(entry)),
                                getCharset(),
                                model.getCSVSyntax().getDelimiter(), getLength(zip, entry)));

    // And encode
    config.getInput().getHandle();
    
    // Disable visualization
    if (model.getMaximalSizeForComplexOperations() > 0 &&
        config.getInput().getHandle().getNumRows() > model.getMaximalSizeForComplexOperations()) {
        model.setVisualizationEnabled(false);
    }
}
 
源代码16 项目: bazel   文件: AndroidResourceOutputs.java
protected void addEntry(
    String rawName, byte[] content, int storageMethod, @Nullable String comment)
    throws IOException {
  // Fix the path for windows.
  String relativeName = rawName.replace('\\', '/');
  // Make sure the zip entry is not absolute.
  Preconditions.checkArgument(
      !relativeName.startsWith("/"), "Cannot add absolute resources %s", relativeName);
  ZipEntry entry = new ZipEntry(relativeName);
  entry.setMethod(storageMethod);
  entry.setTime(normalizeTime(relativeName));
  entry.setSize(content.length);
  CRC32 crc32 = new CRC32();
  crc32.update(content);
  entry.setCrc(crc32.getValue());
  if (!Strings.isNullOrEmpty(comment)) {
    entry.setComment(comment);
  }

  zip.putNextEntry(entry);
  zip.write(content);
  zip.closeEntry();
}
 
源代码17 项目: 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();
}
 
源代码18 项目: openjdk-jdk9   文件: B7050028.java
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
源代码19 项目: coffee-gb   文件: Cartridge.java
private static int[] loadFile(File file) throws IOException {
    String ext = FilenameUtils.getExtension(file.getName());
    try (InputStream is = new FileInputStream(file)) {
        if ("zip".equalsIgnoreCase(ext)) {
            try (ZipInputStream zis = new ZipInputStream(is)) {
                ZipEntry entry;
                while ((entry = zis.getNextEntry()) != null) {
                    String name = entry.getName();
                    String entryExt = FilenameUtils.getExtension(name);
                    if (Stream.of("gb", "gbc", "rom").anyMatch(e -> e.equalsIgnoreCase(entryExt))) {
                        return load(zis, (int) entry.getSize());
                    }
                    zis.closeEntry();
                }
            }
            throw new IllegalArgumentException("Can't find ROM file inside the zip.");
        } else {
            return load(is, (int) file.length());
        }
    }
}
 
源代码20 项目: flink   文件: PackagedProgramTest.java
@Test
public void testExtractContainedLibraries() throws Exception {
	String s = "testExtractContainedLibraries";
	byte[] nestedJarContent = s.getBytes(ConfigConstants.DEFAULT_CHARSET);
	File fakeJar = temporaryFolder.newFile("test.jar");
	try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fakeJar))) {
		ZipEntry entry = new ZipEntry("lib/internalTest.jar");
		zos.putNextEntry(entry);
		zos.write(nestedJarContent);
		zos.closeEntry();
	}

	final List<File> files = PackagedProgram.extractContainedLibraries(fakeJar.toURI().toURL());
	Assert.assertEquals(1, files.size());
	Assert.assertArrayEquals(nestedJarContent, Files.readAllBytes(files.iterator().next().toPath()));
}
 
源代码21 项目: nd4j   文件: ZipTests.java
@Test
public void testZip() throws Exception {

    File testFile = File.createTempFile("adasda","Dsdasdea");

    INDArray arr = Nd4j.create(new double[]{1,2,3,4,5,6,7,8,9,0});

    final FileOutputStream fileOut = new FileOutputStream(testFile);
    final ZipOutputStream zipOut = new ZipOutputStream(fileOut);
    zipOut.putNextEntry(new ZipEntry("params"));
    Nd4j.write(zipOut, arr);
    zipOut.flush();
    zipOut.close();


    final FileInputStream fileIn = new FileInputStream(testFile);
    final ZipInputStream zipIn = new ZipInputStream(fileIn);
    ZipEntry entry = zipIn.getNextEntry();
    INDArray read = Nd4j.read(zipIn);
    zipIn.close();


    assertEquals(arr, read);
}
 
源代码22 项目: ghidra   文件: ExtensionUtilsTest.java
/**
 * Create a generic zip that is a valid extension archive. 
 * 
 * @param zipName name of the zip to create
 * @return a zip file
 * @throws IOException if there's an error creating the zip
 */
private File createExtensionZip(String zipName) throws IOException {

	File f = new File(gLayout.getExtensionArchiveDir().getFile(false), zipName + ".zip");
	try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) {
		out.putNextEntry(new ZipEntry(zipName + "/"));
		out.putNextEntry(new ZipEntry(zipName + "/extension.properties"));

		StringBuilder sb = new StringBuilder();
		sb.append("name:" + zipName);
		byte[] data = sb.toString().getBytes();
		out.write(data, 0, data.length);
		out.closeEntry();
	}

	return f;
}
 
源代码23 项目: atlas   文件: Dex.java
/**
 * 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);
    }
}
 
源代码24 项目: DevUtils   文件: ZipUtils.java
/**
 * 获取压缩文件中的注释链表
 * @param zipFile 压缩文件
 * @return 压缩文件中的注释链表
 * @throws Exception 异常时抛出
 */
public static List<String> getComments(final File zipFile) throws Exception {
    if (zipFile == null) return null;
    List<String> comments = new ArrayList<>();
    Enumeration<?> entries = new ZipFile(zipFile).entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = ((ZipEntry) entries.nextElement());
        comments.add(entry.getComment());
    }
    return comments;
}
 
private void assertExistingJarFile(Path mtaArchiveFile, String fileName, byte[] expectedContent) throws IOException {
    try (JarInputStream in = new JarInputStream(Files.newInputStream(mtaArchiveFile))) {
        for (ZipEntry e; (e = in.getNextEntry()) != null;) {
            if (fileName.equals(e.getName()) && !e.isDirectory()) {
                Assertions.assertArrayEquals(expectedContent, IOUtils.toByteArray(in));
                return;
            }
        }
        throw new AssertionError(MessageFormat.format("Zip archive file \"{0}\" could not be found", fileName));
    }
}
 
private InputStream getUnwrappedClosedInputStream() throws IOException {
    File file = new File("test/webresources/non-static-resources.jar");
    JarFile jarFile = JreCompat.getInstance().jarFileNewInstance(file);
    ZipEntry jarEntry = jarFile.getEntry("META-INF/MANIFEST.MF");
    InputStream unwrapped = jarFile.getInputStream(jarEntry);
    unwrapped.close();
    jarFile.close();
    return unwrapped;
}
 
源代码27 项目: netbeans   文件: TestServer.java
private static void writeFile(ZipOutputStream zip, String name, int size) throws IOException {
    Random random = new Random();
    zip.putNextEntry(new ZipEntry(name));
    for (int i = 0; i < size; i++) {
        zip.write(random.nextInt(Integer.MAX_VALUE - 1) + 1);
    }
    zip.closeEntry();
}
 
源代码28 项目: zuihou-admin-cloud   文件: ZipUtils.java
private static void zipFiles(ZipOutputStream out, String path, File... srcFiles) {
    path = path.replaceAll("\\*", SLASH);
    if (!path.endsWith(SLASH)) {
        path += SLASH;
    }
    byte[] buf = new byte[1024];
    try {
        for (File srcFile : srcFiles) {
            if (srcFile.isDirectory()) {
                File[] files = srcFile.listFiles();
                String srcPath = srcFile.getName();
                srcPath = srcPath.replaceAll("\\*", SLASH);
                if (!srcPath.endsWith(SLASH)) {
                    srcPath += SLASH;
                }
                out.putNextEntry(new ZipEntry(path + srcPath));
                zipFiles(out, path + srcPath, files);
            } else {
                try (FileInputStream in = new FileInputStream(srcFile)) {
                    out.putNextEntry(new ZipEntry(path + srcFile.getName()));
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.closeEntry();
                }
            }
        }
    } catch (Exception e) {
        log.info("ZipUtils error {} ", e);
    }
}
 
源代码29 项目: karate   文件: JobUtils.java
private static void zip(File fileToZip, String fileName, ZipOutputStream zipOut, int level) throws IOException {
    if (fileToZip.isHidden()) {
        return;
    }
    if (fileToZip.isDirectory()) {
        String entryName = fileName;
        zipOut.putNextEntry(new ZipEntry(entryName + "/"));
        zipOut.closeEntry();
        File[] children = fileToZip.listFiles();
        for (File childFile : children) {
            String childFileName = childFile.getName();
            // TODO improve ?
            if (childFileName.equals("target") || childFileName.equals("build")) {
                continue;
            }
            if (level != 0) {
                childFileName = entryName + "/" + childFileName;
            }
            zip(childFile, childFileName, zipOut, level + 1);
        }
        return;
    }
    ZipEntry zipEntry = new ZipEntry(fileName);
    zipOut.putNextEntry(zipEntry);
    FileInputStream fis = new FileInputStream(fileToZip);
    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zipOut.write(bytes, 0, length);
    }
    fis.close();
}
 
源代码30 项目: fingen   文件: FileUtils.java
public static void unzip(String zipFile, String outputFile) throws IOException {
    try {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
        try {
            ZipEntry ze;
            while ((ze = zin.getNextEntry()) != null) {

                if (ze.isDirectory()) {
                    File unzipFile = new File(outputFile);
                    if(!unzipFile.isDirectory()) {
                        unzipFile.mkdirs();
                    }
                }
                else {
                    FileOutputStream fout = new FileOutputStream(outputFile, false);
                    BufferedOutputStream bufout = new BufferedOutputStream(fout);
                    try {

                        byte[] buffer = new byte[2048];
                        int read;
                        while ((read = zin.read(buffer)) != -1) {
                            bufout.write(buffer, 0, read);
                        }
                    }
                    finally {
                        zin.closeEntry();
                        bufout.close();
                        fout.close();
                    }
                }
            }
        }
        finally {
            zin.close();
        }
    }
    catch (Exception e) {
        Log.e(TAG, "Unzip exception", e);
    }
}
 
 类所在包
 同包方法