压缩文件:
01 | import java.io.File; |
02 | import java.io.FileInputStream; |
03 | import java.io.FileOutputStream; |
04 | import java.io.IOException; |
05 | import java.io.InputStream; |
06 | import java.nio.charset.Charset; |
07 | import java.util.zip.ZipEntry; |
08 | import java.util.zip.ZipOutputStream; |
09 | |
10 | public class ZipOutputStreamTest { |
11 | |
12 | public static void main(String args[]) throws IOException { |
13 | test1(); |
14 | test2(); |
15 | } |
16 | |
17 | public static void test1() throws IOException { |
18 | ZipOutputStream zos = new ZipOutputStream( new FileOutputStream( "D:\\testZip.zip" ), Charset.forName( "GBK" )); |
19 | //实例化一个名称为ab.txt的ZipEntry对象 |
20 | ZipEntry entry = new ZipEntry( "ab.txt" ); |
21 | //设置注释 |
22 | zos.setComment( "zip测试for单个文件" ); |
23 | //把生成的ZipEntry对象加入到压缩文件中,而之后往压缩文件中写入的内容都会放在这个ZipEntry对象里面 |
24 | zos.putNextEntry(entry); |
25 | InputStream is = new FileInputStream( "D:\\ab.txt" ); |
26 | int len = 0 ; |
27 | while ((len = is.read()) != - 1 ) |
28 | zos.write(len); |
29 | is.close(); |
30 | zos.close(); |
31 | } |
32 | |
33 | public static void test2() throws IOException { |
34 | File inFile = new File( "D:\\test" ); |
35 | ZipOutputStream zos = new ZipOutputStream( new FileOutputStream( "D:\\test.zip" ), Charset.forName( "GBK" )); |
36 | zos.setComment( "多文件处理" ); |
37 | zipFile(inFile, zos, "" ); |
38 | zos.close(); |
39 | } |
40 | |
41 | public static void zipFile(File inFile, ZipOutputStream zos, String dir) throws IOException { |
42 | if (inFile.isDirectory()) { |
43 | File[] files = inFile.listFiles(); |
44 | for (File file:files) |
45 | zipFile(file, zos, dir + "\\" + inFile.getName()); |
46 | } else { |
47 | String entryName = null ; |
48 | if (! "" .equals(dir)) |
49 | entryName = dir + "\\" + inFile.getName(); |
50 | else |
51 | entryName = inFile.getName(); |
52 | ZipEntry entry = new ZipEntry(entryName); |
53 | zos.putNextEntry(entry); |
54 | InputStream is = new FileInputStream(inFile); |
55 | int len = 0 ; |
56 | while ((len = is.read()) != - 1 ) |
57 | zos.write(len); |
58 | is.close(); |
59 | } |
60 | |
61 | } |
62 | |
63 | } |