12

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.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142

3 Answers3

29

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"));
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
6

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;
}
Sathiamoorthy
  • 8,831
  • 9
  • 65
  • 77
1

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.

Coffee Monkey
  • 481
  • 2
  • 7