I want to zip a folder into a zip file with java.util.zip
tools.
I have already tried to read org.gradle.api.tasks.bundling.Zip
in Gradle, but I cannot understand it at all.
Is there any code or opensource third-party tool that can zip a directory tree?
Asked
Active
Viewed 137 times
-1

Teddy Li
- 9
- 1
- 3
-
Edit: I guess I can handle it with `java.nio.file.Path` and `java.nio.file.Files.copy(java.nio.file.Path, java.nio.file.Path)`, but I don't know how to write it detailedly. – Teddy Li Jun 11 '21 at 13:58
2 Answers
1
You can try using ZipOutputStream to create zip.
List<String> srcFiles = Arrays.asList("test1.txt", "test2.txt"); // List of all files
FileOutputStream fos = new FileOutputStream("multiCompressed.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
for (String srcFile : srcFiles) {
File fileToZip = new File(srcFile);
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
Since you have to zip a folder, you can read all the files inside folder and put inside list(Call method instead of hard coding file names in list ).
Below code I have written to read file from all folder and sub folder, You can make change in logic according to your requirements.
String path = "folderpath"
File dir = new File(path);
List<String> srcFiles = populateFilesList(dir);
private List<String> populateFilesList(File dir) throws IOException {
List filesListInDir = new ArrayList<String>();
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile())
{
filesListInDir.add(file.getAbsolutePath());
}
else
{
populateFilesList(file);
}
}
return filesListInDir;
}
Please try this and let me know if you face any issue.

Vishal Yadav
- 72
- 9
-
Is this way available to copy a file tree correctly? For example: `E:\root\a.txt` will be zipped into entry `a` while `E:\root\c\d\e.jar` will be zipped into entry `c/d/e.jar` instead of `e.jar`. That's what I want. – Teddy Li Jun 12 '21 at 00:55
0
What about use this lib Zeroturnaround Zip library Then you will zip your folder just a one line:
ZipUtil.pack(new File("D:\sourceFolder\"), new File("D:\generatedZipFile.zip"));

mesunmoon
- 35
- 1
- 5
-
Plagiarizing [another answer](https://stackoverflow.com/a/62985640/1831987) is not good form. – VGR Jun 11 '21 at 14:55
-