1
2
3
4
5
6 package org.tailormap.api.service;
7
8 import java.io.File;
9 import java.io.IOException;
10 import java.lang.invoke.MethodHandles;
11 import java.nio.file.Files;
12 import java.nio.file.Path;
13 import java.util.stream.Stream;
14 import java.util.zip.ZipEntry;
15 import java.util.zip.ZipOutputStream;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18 import org.springframework.stereotype.Service;
19
20
21 @Service
22 public class ZipService {
23 private static final Logger logger =
24 LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
25
26
27
28
29
30
31
32 public void zipDirectory(Path sourceDir, Path zipFile) throws IOException {
33 try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipFile));
34 Stream<Path> pathStream = Files.walk(sourceDir)) {
35 pathStream.filter(Files::isRegularFile).forEach(path -> {
36 String entryName = sourceDir.relativize(path).toString().replace(File.separatorChar, '/');
37 try {
38 logger.trace("Adding file {} to zip {}", path, zipFile);
39 zos.putNextEntry(new ZipEntry(entryName));
40 Files.copy(path, zos);
41 zos.closeEntry();
42 } catch (IOException e) {
43 throw new RuntimeException("Failed to add file to zip: " + path, e);
44 }
45 });
46 } catch (RuntimeException e) {
47 if (e.getCause() instanceof IOException ioException) {
48 throw ioException;
49 }
50 throw e;
51 }
52 }
53 }