ZipEntry to File
Solution 1
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"));
Solution 2
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;
}
Solution 3
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.
J Fabian Meier
Software architecture and development tools specialist for a large insurance company. Interested in Java architecture, build processes and improving dependency management. Using Maven, Sonatype Nexus, Artifactory. Used to be in academia, working on discrete optimization (hub location). PhD in differential topology. Maths Olympiad enthusiast.
Updated on July 27, 2022Comments
-
J Fabian Meier almost 2 years
Is there a direct way to unpack a
java.util.zip.ZipEntry
to aFile
?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 about 8 yearsThis means: No, there is no library function?
-
Acuna almost 6 yearsYes, @JFMeier yes, right you) There's much of library functions which Java don't have.