forked from JavaDevTeam/notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava-compress.java
More file actions
87 lines (81 loc) · 2.81 KB
/
java-compress.java
File metadata and controls
87 lines (81 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
-----------------------------
压缩算法 |
-----------------------------
ZipOutputStream
ZipInputStream
GZIPOutputStream
GZIPInputStream
-----------------------------
把多个文件压缩为zip |
-----------------------------
public static void packet(Path[] files, Path zipFile) throws IOException {
OutputStream outputStream = Files.newOutputStream(zipFile, StandardOpenOption.CREATE_NEW);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
for (Path file : files) {
InputStream inputStream = Files.newInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getFileName().toString());
zipOutputStream.putNextEntry(zipEntry);
int len;
byte[] buffer = new byte[1024 * 10];
while ((len = inputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
inputStream.close();
}
zipOutputStream.closeEntry();
zipOutputStream.close();
outputStream.close();
}
------------------------------------------
GIZ压缩/解压缩 |
------------------------------------------
/**
* 压缩
* @param data
* @return
* @throws IOException
*/
public static byte[] gZip(byte[] data) throws IOException {
byte[] bytes = null;
ByteArrayOutputStream byteArrayOutputStream = null;
GZIPOutputStream gzipOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gzipOutputStream.write(data);
gzipOutputStream.finish();
bytes = byteArrayOutputStream.toByteArray();
} finally {
}
return bytes;
}
/**
* 解压缩
* @param data
* @return
* @throws IOException
*/
public static byte[] unGZip(byte[] data) throws IOException {
byte[] bytes = null;
ByteArrayInputStream byteArrayInputStream = null;
GZIPInputStream gzipInputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayInputStream = new ByteArrayInputStream(data);
gzipInputStream = new GZIPInputStream(byteArrayInputStream);
byte[] buf = new byte[1024];
int num = -1;
byteArrayOutputStream = new ByteArrayOutputStream();
while ((num = gzipInputStream.read(buf, 0, buf.length)) != -1)
{
byteArrayOutputStream.write(buf, 0, num);
}
bytes = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.flush();
} finally {
byteArrayInputStream.close();
gzipInputStream.close();
byteArrayOutputStream.close();
}
return bytes;
}