1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.appender.rolling.action;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.util.Objects;
24 import java.util.zip.ZipEntry;
25 import java.util.zip.ZipOutputStream;
26
27
28
29
30
31 public final class ZipCompressAction extends AbstractAction {
32
33 private static final int BUF_SIZE = 8102;
34
35
36
37
38 private final File source;
39
40
41
42
43 private final File destination;
44
45
46
47
48 private final boolean deleteSource;
49
50
51
52
53 private final int level;
54
55
56
57
58
59
60
61
62
63
64 public ZipCompressAction(final File source, final File destination, final boolean deleteSource, final int level) {
65 Objects.requireNonNull(source, "source");
66 Objects.requireNonNull(destination, "destination");
67
68 this.source = source;
69 this.destination = destination;
70 this.deleteSource = deleteSource;
71 this.level = level;
72 }
73
74
75
76
77
78
79
80 @Override
81 public boolean execute() throws IOException {
82 return execute(source, destination, deleteSource, level);
83 }
84
85
86
87
88
89
90
91
92
93
94
95
96 public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level)
97 throws IOException {
98 if (source.exists()) {
99 try (final FileInputStream fis = new FileInputStream(source);
100 final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destination))) {
101 zos.setLevel(level);
102
103 final ZipEntry zipEntry = new ZipEntry(source.getName());
104 zos.putNextEntry(zipEntry);
105
106 final byte[] inbuf = new byte[BUF_SIZE];
107 int n;
108
109 while ((n = fis.read(inbuf)) != -1) {
110 zos.write(inbuf, 0, n);
111 }
112 }
113
114 if (deleteSource && !source.delete()) {
115 LOGGER.warn("Unable to delete " + source.toString() + '.');
116 }
117
118 return true;
119 }
120
121 return false;
122 }
123
124
125
126
127
128
129 @Override
130 protected void reportException(final Exception ex) {
131 LOGGER.warn("Exception during compression of '" + source.toString() + "'.", ex);
132 }
133
134 @Override
135 public String toString() {
136 return ZipCompressAction.class.getSimpleName() + '[' + source + " to " + destination
137 + ", level=" + level + ", deleteSource=" + deleteSource + ']';
138 }
139 }