JAVA 压缩文件

 

压缩文件:

 
01import java.io.File;
02import java.io.FileInputStream;
03import java.io.FileOutputStream;
04import java.io.IOException;
05import java.io.InputStream;
06import java.nio.charset.Charset;
07import java.util.zip.ZipEntry;
08import java.util.zip.ZipOutputStream;
09  
10public 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}
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值