J Fabian Meier
J Fabian Meier

Reputation: 35785

ZipEntry to File

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.

Upvotes: 12

Views: 26116

Answers (3)

Sathiamoorthy
Sathiamoorthy

Reputation: 11542

Use the below code to extract the "zip file" into File's then add 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;
}

Upvotes: 6

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

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"));

Upvotes: 31

Coffee Monkey
Coffee Monkey

Reputation: 472

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.

Upvotes: 1

Related Questions