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

TheAlexGamer :

Heyy! Before you go and report this as a duplicate: I researched for hours and hours and yes there are a LOT of sites, questions and videos about that, but none of those can help me.

I used diffrent techniques already 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 and all files from other subfolders directly into the zip, so when i cliuck 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.

Jubick :

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>() {
       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

./somethigelse/ First folder

./somethingother/ Second folder

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=311206&siteId=1