解压缩Zip包异步任务类

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.util.Log;

/**    解压缩Zip包异步任务类
 * @author xly
 */
public class ZipExtractorTask extends AsyncTask<Void, Integer, Long> {
    private final String TAG = "ZipExtractorTask";
    private final File input;
    private final File output;
    private final ProgressDialog dialog;
    private int progress;
    private final Context context;
    private boolean replaceAll;
    public ZipExtractorTask(String zipPath, String unzipPath, Context context, boolean replaceAll) {
        super();
        this.input = new File(zipPath);
        this.output = new File(unzipPath);
        if (!this.output.exists()) {        //解压的目的文件夹不存在
            if (!this.output.mkdirs()) {    //解压的目的文件夹未创建
                Log.d(TAG, "file to make directories : " + output.getAbsolutePath());
            }
        }
        if (context != null) {
            this.dialog = new ProgressDialog(context);
        } else {
            dialog = null;
        }
        this.context = context;
        this.replaceAll = replaceAll;
    }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (dialog != null) {
            dialog.setTitle(R.string.extracting);
            dialog.setMessage("请稍候");
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    cancel(true);
                }
            });
            dialog.show();
        }
    }

    @Override
    protected Long doInBackground(Void... params) {
        return unzip();
    }
    
    @Override
    protected void onPostExecute(Long result) {
        super.onPostExecute(result);
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (isCancelled()) {
            return;
        }
    }
    
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if (dialog == null) {
            return;
        }
        if (values.length > 1) {
            dialog.setMax(values[1].intValue());
        } else {
            dialog.setProgress(values[0].intValue());
        }
    }
    
    @SuppressWarnings("unchecked")
    private long unzip() {
        long extractedSize = 0L;
        Enumeration<ZipEntry> entries;
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(this.input);                    //根据路径获取要解压的Zip文件
            long uncompressedSize = getOriginalSize(zipFile);    //未处理(解压)的Zip文件大小
            publishProgress(0, (int) uncompressedSize);            //更新ProgressDialog的进度数据
            entries = (Enumeration<ZipEntry>) zipFile.entries();//读取Zip包中的所有文件
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (entry.isDirectory()) {
                    continue;
                }
                File destination = new File(output, entry.getName());
                if (!destination.getParentFile().exists()) {
                    destination.getParentFile().mkdirs();
                }
                if (destination.exists() && context != null && replaceAll) {
                    
                }
                ProgressReportintOutputStream outputStream = new ProgressReportintOutputStream(destination);
                extractedSize += copy(zipFile.getInputStream(entry), outputStream);
                outputStream.close();
            }
        } catch (ZipException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                zipFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return extractedSize;
    }
    
    /**
     * @param file
     * @return 文件原始大小
     */
    @SuppressWarnings("unchecked")
    private long getOriginalSize(ZipFile zipFile) {    
        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries();
        long originalSize = 01;
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getSize() >= 0) {
                originalSize += entry.getSize();
            }
        }
        return originalSize;
    }
    
    private int copy(InputStream input, OutputStream output) {
        byte[] buffer = new byte[1024 * 8];
        BufferedInputStream in = new BufferedInputStream(input, 1024 * 8);
        BufferedOutputStream out = new BufferedOutputStream(output, 1024 * 8);
        int count = 0, n = 0;
        try {
            while ((n = in.read(buffer, 0, 1024 * 8)) != -1) {
                out.write(buffer, 0, n);
                count += n;
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        return count;
    }
    
    private final class ProgressReportintOutputStream extends FileOutputStream {
        public ProgressReportintOutputStream(File file) throws FileNotFoundException {
            super(file);
        }
        @Override
        public void write(byte[] buffer, int byteOffset, int byteCount)
                throws IOException {
            super.write(buffer, byteOffset, byteCount);
            progress += byteCount;
            publishProgress(progress);
        }
    }
}

Java调用Zip类批量压缩多个文件,此前有一个是压缩单个文件,也可参考,相关代码中可找到此源码。   public class ZipDemo extends JFrame{   JFileChooser fileChooser; //文件选择器   JList fileList; //待压缩的文件列表   Vector files; //文件数据(待压缩文件)   JButton jbAdd; //增加文件按钮   JButton jbDelete; //删除文件按钮   JButton jbZip; //压缩按钮   JTextField target; //目标文件文本域   public ZipDemo(){   super("用ZIP压缩多个文件"); //调用父类构造函数   fileChooser=new JFileChooser(); //实例化文件选择器   files=new Vector(); //实例化文件数据Vector   fileList=new JList(files); //实例化已选择文件列表   jbAdd=new JButton("增加"); //实例化按钮组件   jbDelete=new JButton("删除");   jbZip=new JButton("压缩");   target=new JTextField(18);   JPanel panel=new JPanel(); //实例化面板,用于容纳按钮   panel.add(jbAdd); //增加组件到面板上   panel.add(jbDelete);   panel.add(jbZip);   JPanel panel2=new JPanel();   panel2.add(new JLabel("目标文件"));   panel2.add(target);   JScrollPane jsp=new JScrollPane(fileList);   Container container=getContentPane(); //得到容器   container.add(panel2,BorderLayout.NORTH); //增加组件到容器   container.add(jsp,BorderLayout.CENTER);   container.add(panel,BorderLayout.SOUTH);   jsp.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //设置边界
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值