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.helper;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23
24 import java.util.zip.ZipEntry;
25 import java.util.zip.ZipOutputStream;
26
27
28
29
30
31 public final class ZipCompressAction extends ActionBase {
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
54
55
56
57
58 public ZipCompressAction(final File source, final File destination, final boolean deleteSource) {
59 if (source == null) {
60 throw new NullPointerException("source");
61 }
62
63 if (destination == null) {
64 throw new NullPointerException("destination");
65 }
66
67 this.source = source;
68 this.destination = destination;
69 this.deleteSource = deleteSource;
70 }
71
72
73
74
75
76
77
78 public boolean execute() throws IOException {
79 return execute(source, destination, deleteSource);
80 }
81
82
83
84
85
86
87
88
89
90
91
92 public static boolean execute(final File source, final File destination, final boolean deleteSource)
93 throws IOException {
94 if (source.exists()) {
95 FileInputStream fis = new FileInputStream(source);
96 FileOutputStream fos = new FileOutputStream(destination);
97 ZipOutputStream zos = new ZipOutputStream(fos);
98
99 ZipEntry zipEntry = new ZipEntry(source.getName());
100 zos.putNextEntry(zipEntry);
101
102 byte[] inbuf = new byte[BUF_SIZE];
103 int n;
104
105 while ((n = fis.read(inbuf)) != -1) {
106 zos.write(inbuf, 0, n);
107 }
108
109 zos.close();
110 fis.close();
111
112 if (deleteSource && !source.delete()) {
113 LOGGER.warn("Unable to delete " + source.toString() + ".");
114 }
115
116 return true;
117 }
118
119 return false;
120 }
121
122
123
124
125
126
127 protected void reportException(final Exception ex) {
128 LOGGER.warn("Exception during compression of '" + source.toString() + "'.", ex);
129 }
130 }