1import java.io.FileOutputStream;
2import java.io.IOException;
3import java.nio.file.*;
4import java.nio.file.attribute.BasicFileAttributes;
5import java.util.zip.ZipEntry;
6import java.util.zip.ZipOutputStream;
7
8public class ZipCompress {
9 public static void compress(String dirPath) {
10 final Path sourceDir = Paths.get(dirPath);
11 String zipFileName = dirPath.concat(".zip");
12 try {
13 final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
14 Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
15 @Override
16 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
17 try {
18 Path targetFile = sourceDir.relativize(file);
19 outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
20 byte[] bytes = Files.readAllBytes(file);
21 outputStream.write(bytes, 0, bytes.length);
22 outputStream.closeEntry();
23 } catch (IOException e) {
24 e.printStackTrace();
25 }
26 return FileVisitResult.CONTINUE;
27 }
28 });
29 outputStream.close();
30 } catch (IOException e) {
31 e.printStackTrace();
32 }
33 }
34}
1import java.io.BufferedOutputStream;
2import java.io.File;
3import java.io.FileOutputStream;
4import java.nio.file.Files;
5import java.nio.file.Paths;
6import java.util.ArrayList;
7import java.util.List;
8import java.util.zip.ZipEntry;
9import java.util.zip.ZipOutputStream;
10
11public class zip {
12
13 public static void main(String[] args) {
14 zipFolder(mapFolder("Test"));
15
16 System.out.println("Done");
17 }
18
19 public static List<String> mapFolder(String path, boolean includeEmptyFolders) {
20 List<String> map = new ArrayList<String>();
21 List<String> unmappedDirs = new ArrayList<String>();
22 File[] items = new File(path).listFiles();
23
24 if (!path.substring(path.length() - 1).equals("/")) {
25 path += "/";
26 }
27
28 if (items != null) {
29 for (File item : items) {
30 if (item.isFile()) {
31 map.add(path+item.getName());
32 } else {
33 unmappedDirs.add(path+item.getName());
34 }
35 }
36
37 if (!unmappedDirs.isEmpty()) {
38 for (String folder : unmappedDirs) {
39 List<String> temp = mapFolder(folder, includeEmptyFolders);
40 if (!temp.isEmpty()) {
41 for (String item : temp)
42 map.add(item);
43 } else if (includeEmptyFolders == true) {
44 map.add(folder+"/");
45 }
46 }
47 }
48 }
49 return map;
50 }
51
52 public static void zipFolder(String zipPath, List<String> items) {
53 try {
54 FileOutputStream f = new FileOutputStream(zipPath);
55 ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f));
56
57 for (String item : items) {
58 String contents = String.join("\n", Files.readAllLines(Paths.get(item)));
59 zip.putNextEntry(new ZipEntry(item));
60
61 byte[] data = contents.getBytes();
62 zip.write(data, 0, data.length);
63 zip.closeEntry();
64 }
65
66 zip.close();
67 f.close();
68 } catch(Exception e) {
69 System.out.println(e.getMessage());
70 }
71 }
72}