java解压缩ZIP

来源:互联网 发布:php 数组取值 编辑:程序博客网 时间:2024/05/21 10:03

今天做了个东西,用到java中的解ZIP压缩功能,特写下来。

首先应该构造文件输入流,如下:

FileInputStream fis = new FileInputStream("文件路径");
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); 

构造ZIP目录类和文件输出流

ZipEntry entry;

BufferedOutputStream dest = null;

然后读取ZIP文件,看包里有几个文件,然后在建立这些文件(如果压缩包压缩的是个文件夹,要首先建立这个文件夹,然后在文件夹下建立相应的文件)

entry = zis.getNextEntry();
            File folder = new File(pth+ entry.getName());
            folder.mkdir();

while ( (entry = zis.getNextEntry()) != null)
            {

             File file = new File(path+ entry.getName());

再构建文件输出流,然后通过缓存输出流进行写文件

byte data[] = new byte[BUFFER];

                FileOutputStream fos = new FileOutputStream(path + "/" + entry.getName());

                dest = new BufferedOutputStream(fos, BUFFER);
                while ( (count = zis.read(data)) != -1)
                {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                fos.close();
详细的代码如下所示:

package net.action;


import java.io.*;
import java.util.zip.*;


public class Test
{
    static final int BUFFER = 2048;

    private static int flag = 0;

    private static String path = "C:/temp/";

    public static void main(String argv[])
    {
        try
        {
            BufferedOutputStream dest = null;
            //构造文件输入流
            FileInputStream fis = new FileInputStream("C://temp//20070530.zip");
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
           
            ZipEntry entry;

            entry = zis.getNextEntry();
            File folder = new File(path + entry.getName());
            folder.mkdir();

            while ( (entry = zis.getNextEntry()) != null)
            {
                System.out.println("Extracting: " + entry);

                File file = new File(path + entry.getName());

                int count;
                byte data[] = new byte[BUFFER];

                FileOutputStream fos = new FileOutputStream(path  + entry.getName());

                dest = new BufferedOutputStream(fos, BUFFER);
                while ( (count = zis.read(data)) != -1)
                {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                fos.close();

            }
            zis.close();
            fis.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

 

原创粉丝点击