java.util.zip.ZipEntry Java Examples

The following examples show how to use java.util.zip.ZipEntry. 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 Project: capsule-maven-plugin   Author: chrisdchristo   File: Mojo.java    License: MIT License 6 votes vote down vote up
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;
	}
 
Example #2
Source Project: jackrabbit-filevault   Author: apache   File: UpdateableZipFile.java    License: Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #3
Source Project: AndroidUtilCode   Author: Blankj   File: ZipUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source Project: Knowage-Server   Author: KnowageLabs   File: DocumentExecutionResource.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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();
	}
 
Example #5
Source Project: sarl   Author: sarl   File: SARLRuntime.java    License: Apache License 2.0 6 votes vote down vote up
/** 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;
}
 
Example #6
Source Project: buck   Author: facebook   File: ZipOutputStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #7
Source Project: microprofile-starter   Author: eclipse   File: ZipFileCreator.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #8
Source Project: vespa   Author: vespa-engine   File: BundleTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source Project: NullAway   Author: uber   File: DefinitelyDerefedParamsDriver.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example #10
Source Project: LibScout   Author: reddr   File: ApkUtils.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source Project: zuihou-admin-boot   Author: zuihou   File: ZipUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 通过流打包下载文件
 *
 * @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();
        }
    }
}
 
Example #12
Source Project: native-obfuscator   Author: radioegor146   File: TestExtraTime.java    License: GNU General Public License v3.0 6 votes vote down vote up
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());
        }
    }
}
 
Example #13
Source Project: nd4j   Author: deeplearning4j   File: JarResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #14
Source Project: tracecompass   Author: tracecompass   File: TestDirectoryStructureUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
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();
            }
        }
    }
}
 
Example #15
Source Project: arx   Author: arx-deidentifier   File: WorkerLoad.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #16
Source Project: bazel   Author: bazelbuild   File: AndroidResourceOutputs.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #17
Source Project: shrinker   Author: yrom   File: JarProcessor.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #18
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: B7050028.java    License: GNU General Public License v2.0 6 votes vote down vote up
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()));
}
 
Example #19
Source Project: coffee-gb   Author: trekawek   File: Cartridge.java    License: MIT License 6 votes vote down vote up
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());
        }
    }
}
 
Example #20
Source Project: flink   Author: apache   File: PackagedProgramTest.java    License: Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example #21
Source Project: nd4j   Author: deeplearning4j   File: ZipTests.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #22
Source Project: ghidra   Author: NationalSecurityAgency   File: ExtensionUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source Project: atlas   Author: alibaba   File: Dex.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new dex buffer from the dex file {@code file}.
 */
public Dex(File file) throws IOException{
    if (FileUtils.hasArchiveSuffix(file.getName())) {
        ZipFile zipFile = new ZipFile(file);
        ZipEntry entry = zipFile.getEntry(DexFormat.DEX_IN_JAR_NAME);
        if (entry != null) {
            loadFrom(zipFile.getInputStream(entry));
            zipFile.close();
        } else {
            throw new DexException2("Expected " + DexFormat.DEX_IN_JAR_NAME + " in " + file);
        }
    } else if (file.getName().endsWith(".dex")) {
        loadFrom(new FileInputStream(file));
    } else {
        throw new DexException2("unknown output extension: " + file);
    }
}
 
Example #24
Source Project: DevUtils   Author: afkT   File: ZipUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取压缩文件中的注释链表
 * @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;
}
 
Example #25
Source Project: multiapps-controller   Author: cloudfoundry-incubator   File: MtaArchiveBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
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));
    }
}
 
Example #26
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: TestJarInputStreamWrapper.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example #27
Source Project: netbeans   Author: apache   File: TestServer.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #28
Source Project: zuihou-admin-cloud   Author: zuihou   File: ZipUtils.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #29
Source Project: karate   Author: intuit   File: JobUtils.java    License: MIT License 5 votes vote down vote up
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();
}
 
Example #30
Source Project: fingen   Author: YoshiOne   File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}