zip file unzip file demo

来源:互联网 发布:linux 安装syslog 编辑:程序博客网 时间:2024/06/10 15:24

 

some demo here (http://www.example-code.com/java/zip.asp)
make zip file 
import java.io.*;
import java.util.zip.*;

class  makeZipFile {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println(
   "Usage: java makeZipFile [files to be zipped] [filename after zip] ");
            return;
        }
        try {
            String filename = args[0];
            String zipfilename = args[1];
            makeZipFile list = new makeZipFile( );
            list.doZip(filename,zipfilename);
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void doZip(String filename,String zipfilename) {
        try {
            byte[] buf = new byte[1024];
            FileInputStream fis = new FileInputStream(filename);
            fis.read(buf,0,buf.length);
            
            CRC32 crc = new CRC32();
            ZipOutputStream s = new ZipOutputStream(
                    (OutputStream)new FileOutputStream(zipfilename));
            
            s.setLevel(6);
            
            ZipEntry entry = new ZipEntry(filename);
            entry.setSize((long)buf.length);
            crc.reset();
            crc.update(buf);
            entry.setCrccrc.getValue());
            s.putNextEntry(entry);
            s.write(buf, 0, buf.length);
            s.finish();
            s.close();
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.example.util.zip;
02. 
03.import java.util.zip.ZipFile;
04.import java.util.zip.ZipEntry;
05.import java.util.Enumeration;
06.import java.io.*;
07. 
08.public class ZipFileUnzipDemo {
09.public static void main(String[] args) {
10.String zipname = "data.zip";
11. 
12.try {
13.ZipFile zipFile = new ZipFile(zipname);
14.Enumeration enumeration = zipFile.entries();
15. 
16.while (enumeration.hasMoreElements()) {
17.ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
18.System.out.println("Unzipping: "+ zipEntry.getName());
19. 
20.BufferedInputStream bis = newBufferedInputStream(zipFile.getInputStream(zipEntry));
21. 
22.int size;
23.byte[] buffer = new byte[2048];
24. 
25.FileOutputStream fos = newFileOutputStream(zipEntry.getName());
26.BufferedOutputStream bos = newBufferedOutputStream(fos, buffer.length);
27. 
28.while((size = bis.read(buffer, 0, buffer.length)) != -1) {
29.bos.write(buffer, 0, size);
30.}
31. 
32.bos.flush();
33.bos.close();
34.fos.close();
35. 
36.bis.close();
37.}
38.} catch (IOException e) {
39.e.printStackTrace();
40.}
41.}
42.}

 

原创粉丝点击