javazip

How can I zip a complete directory with all subfolders in Java?


I already used different techniques to create a zip archive, which works great. I also get all files from subdirectories without a problem. But the thing is that I only get all the files listed, without their directories. If I have

/something/somethingelse/text1.txt and /something/somethingother/lol.txt

I want it to be shown in the zip folder exactly like that.

In the zip folder there should be the 2 folders somethingelse and somethingother, containing their file(s). With all the versions I found, it puts all files from other subfolders directly into the zip, so when I click on the .zip it just shows text1.txt and lol.txt, without any folders.

Is there a way that processes a .zip as all the well-known programs for zipping files?

I just want to zip the directory and have everything as it was before, just packed into a zip archive.

I tried out everything I can with my level of Java and also tried some online version. Nothing leads to the result I want.


Solution

  • Here you go:

    private static void zipFolder(Path sourceFolderPath, Path zipPath) throws Exception {
       ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile()));
       Files.walkFileTree(sourceFolderPath, new SimpleFileVisitor<Path>() {
           @Override
           public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
               zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
               Files.copy(file, zos);
               zos.closeEntry();
               return FileVisitResult.CONTINUE;
            }
        });
        zos.close();
     }
    

    ./ Zip

    ./somethingelse/ First folder

    ./somethingother/ Second folder