Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZipEntry to File

Tags:

java

file

zip

Is there a direct way to unpack a java.util.zip.ZipEntry to a File?

I want to specify a location (like "C:\temp\myfile.java") and unpack the Entry to that location.

There is some code with streams on the net, but I would prefer a tested library function.

like image 933
J Fabian Meier Avatar asked Apr 27 '16 12:04

J Fabian Meier


People also ask

How do I get files from ZipEntry?

To read the file represented by a ZipEntry you can obtain an InputStream from the ZipFile like this: ZipEntry zipEntry = zipFile. getEntry("dir/subdir/file1.

What is ZipEntry in Java?

ZipEntry class is used to represent a ZIP file entry.

How do I get InputStream from ZipEntry?

Solution: open input stream from zip file ZipInputStream zipInputStream = ZipInputStream(new FileInputStream(zipfile) , run cycle zipInputStream. getNextEntry() . For every round you have the inputstream for current entry (opened for zip file before); .. This method is more generic than ZipFile.


3 Answers

Use ZipFile class

    ZipFile zf = new ZipFile("zipfile");

Get entry

    ZipEntry e = zf.getEntry("name");

Get inpustream

    InputStream is = zf.getInputStream(e);

Save bytes

    Files.copy(is, Paths.get("C:\\temp\\myfile.java"));
like image 145
Evgeniy Dorofeev Avatar answered Sep 23 '22 15:09

Evgeniy Dorofeev


Use the below code to extract the "zip file" into File's then added in the list using ZipEntry. Hopefully, this will help you.

private List<File> unzip(Resource resource) {
    List<File> files = new ArrayList<>();
    try {
        ZipInputStream zin = new ZipInputStream(resource.getInputStream());
        ZipEntry entry = null;
        while((entry = zin.getNextEntry()) != null) {
            File file = new File(entry.getName());
            FileOutputStream  os = new FileOutputStream(file);
            for (int c = zin.read(); c != -1; c = zin.read()) {
                os.write(c);
            }
            os.close();
            files.add(file);
        }
    } catch (IOException e) {
        log.error("Error while extract the zip: "+e);
    }
    return files;
}
like image 34
Sathia Avatar answered Sep 23 '22 15:09

Sathia


Use ZipInputStream to move to the desired ZipEntry by iterating using the getNextEntry() method. Then use the ZipInputStream.read(...) method to read the bytes for the current ZipEntry. Output those bytes to a FileOutputStream pointing to a file of your choice.

like image 42
Coffee Monkey Avatar answered Sep 25 '22 15:09

Coffee Monkey