解压缩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);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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)); //设置边界
### 回答1: 在Linux中,可以使用unzip命令来解压缩zip。具体命令格式如下: ``` unzip filename.zip ``` 其中,filename.zip为要解压缩zip文件名。执行该命令后,zip将会被解压缩到当前目录下。如果要将zip解压缩到指定目录下,可以使用如下命令: ``` unzip filename.zip -d /path/to/directory ``` 其中,/path/to/directory为指定的目录路径。 ### 回答2: 在Linux中,我们可以使用unzip命令来解压缩zip。unzip命令是一个非常常用的命令,可以解压缩各种型的压缩文件,zip格式。 要解压缩一个zip,我们可以使用以下命令格式: unzip [选项] 压缩文件名.zip 其中,[选项]是可选的,可以为一些附加参数,可以根据需要进行指定。 常用的一些选项括: -n:不覆盖已存在的文件; -o:解压缩时覆盖已存在的文件; -d 目录名:将压缩文件解压缩到指定的目录中。 例如,如果我们有一个名为example.zip的压缩文件,并且想要解压缩到当前目录中,可以使用以下命令: unzip example.zip 这将会将example.zip解压缩到当前目录中。 如果我们想要将example.zip解压缩到一个指定的目录中,可以使用-d选项,例如: unzip example.zip -d /path/to/directory 这将会将example.zip解压缩到/path/to/directory目录中。 总结起来,解压缩zip的命令是unzip,通过指定选项和压缩文件名来实现解压缩操作。 ### 回答3: 在Linux系统中解压缩zip的命令是"unzip"。使用该命令可以将zip文件解压缩并提取其中的文件。 基本的zip解压命令如下: unzip [选项] 压缩.zip 选项: -e:将解压缩的文件提取到当前目录(不含目录结构) -d 目录:将解压缩的文件提取到指定目录 -o:不询问直接覆盖已存在的文件 -q:静默模式,不显示解压缩的详细信息 -v:显示解压缩的详细信息 -f:测试zip文件是否损坏 -p:将解压缩的文件输出到标准输出,可以通过重定向来保存为文件 例如,要解压缩名为"example.zip"的zip,将其中的文件提取到当前目录,可以使用以下命令: unzip example.zip 如果要将文件提取到指定目录"destination",可以使用以下命令: unzip example.zip -d destination 通常情况下,Linux系统都会预装unzip命令,可以直接在终端中使用。如果系统没有预装该命令,可以通过管理器来安装,例如在Ubuntu上使用apt-get: sudo apt-get install unzip 总之,通过unzip命令可以在Linux系统中解压缩zip,提取其中的文件,并且可以根据需求使用不同的选项来控制解压缩过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值