Android Zip4j--Unzip the zip file and display the decompression progress in real time

Source: Internet
Author: User

Zip files are often used in the compressed file format, Android in the network request for high-volume data, usually used to pass the zip file, so that can reduce the consumption of network traffic, speed up the response of the request, but also reduce the storage space requirements, So when we read the zip file back, how to decompress is a problem to solve, although Java itself provides the ZIP related API, but not very strong, so we use the Apache Open source organization zip4j, through this jar package can be very easy to extract zip files.

Back to the project, the project has a need to request a magazine from the server, request back to show the reader, but because the company's own electronic magazine is too large, at least 20M, this is a very large data, so with the server agreed to use the zip to transfer, can reduce the size of the file, Reduce the pressure on the server. I was dealing with the process:

1. Use HttpURLConnection to get the connection to the server and obtain the input stream inputstream.

2. Use the Java Zip stream to convert the InputStream to a zip stream.

3. Record the location of each transfer and save it in a temporary file. (for the continuation of the breakpoint, due to the large amount of data, so to do the breakpoint continued to pass, after detailed)

4. After the loop reads the stream, generate a zip file, unzip the zip file and display the decompression progress in real time.

Through the above four steps to complete the read from the server Zip package, and unzip the zip package to the user show, this article summarizes the final step:


By reading the ZIP4J website demo, you can be informed that this jar package itself is to support the decompression progress of the Read this function. Here is a demo of my own, can be real-time to send out the progress of the decompression, in the interface to update.

First look at the demo of the decompression progress, relatively simple, with the data, the effect wants to do more complex can, for example, according to the progress to draw a progress bar.

This is a certain moment.

Code:

Package Util;import Java.io.file;import Net.lingala.zip4j.core.zipfile;import Net.lingala.zip4j.exception.zipexception;import Net.lingala.zip4j.progress.progressmonitor;import Android.os.bundle;import android.os.handler;import android.os.message;/** * @author rzq * @function Package an unpacking tool class, If you need to compress related methods later, put them in this class  */public class Ziputil{private static final String password = "test123";p ublic static void Unzi Pfilewithprogress (Final File zipfile, final String filePath, Final Handler handler,final Boolean isdeletezip) throws Zipex Ception{zipfile zfile = new ZipFile (ZipFile); Zfile.setfilenamecharset ("GBK"); if (!zfile.isvalidzipfile ()) {//throw New Zipexception ("exception!");} File DestDir = new file (FilePath); // ???? ¼if (Destdir.isdirectory () &&!destdir.exists ()) {Destdir.mkdir ();} if (zfile.isencrypted ()) {Zfile.setpassword (password);//Set Decompression password}final progressmonitor progressmonitor = Zfile.getprogressmonitor (); Thread thread = new Thread (new Runnable () {@Overridepublic void run () {Bundlebundle = NULL; Message msg = Null;try{int Precentdone = 0;if (handler = = null) {return;} Handler.sendemptymessage (Compressstatus.start); while (true) {//Every 50ms, send an extract progress out thread.sleep ();p Recentdone = Progressmonitor.getpercentdone (); bundle = new Bundle (); Bundle.putint (Compressstatus.percent, precentdone); msg = new Message (); msg.what = Compressstatus.handling;msg.setdata (bundle); Handler.sendmessage (msg); Throw the progress through handler if (Precentdone >=) {break;}} Handler.sendemptymessage (compressstatus.completed);} catch (Interruptedexception e) {bundle = new bundle (); bundle.putstring (compressstatus.error_com, E.getmessage ()); msg = New Message (); msg.what = Compressstatus.error;msg.setdata (bundle); Handler.sendmessage (msg); E.printstacktrace ();} Finally{if (isdeletezip) {zipfile.delete ();//delete original compressed File}}}); Thread.Start (); Zfile.setruninthread (true); True in the sub-thread decompression, false main thread decompression Zfile.extractall (FilePath); Unzip the compressed file into filepath ...}} /** * Package Different decompression states * **/ public class compressstatus{    p ublic final static int START = 10000;    public final static int handling = 10001;    publ IC final static int completed = 10002;    public final static int ERROR = 10003;    public F Inal static string PERCENT = "PERCENT";    public final static string error_com = "ERROR";} Package Com.example.zipprogress;import java.io.file;import net.lingala.zip4j.exception.zipexception;import util. Compressstatus;import util. Ziputil;import Android.app.activity;import Android.os.bundle;import Android.os.environment;import Android.os.handler;import android.os.message;import android.widget.textview;/** * @author rzq * @function To update the Ui */public class Mainactivity extends Activity {    textview tv;    string zipfilepath;     @Override     protected void OnCreate (Bundle savedinstancestate) {         super.oncreate (savedinstancestate);        setcontentview (r.layout.activity_main);        TV = (TextView) Findviewbyid (r.id.text_progress);        zipfilepath = Environment.getexternalstoragedirectory (). toString ()                  + "/desktop.zip";        file zipfile = new File (zipfilepath);  & nbsp      try {             Ziputil.unzipfilewithprogress (zipfile,                     environment.getexternalstoragedirectory () + "/mytest/",                     handler, False);        } catch (zipexception e) {            e.printstacktrace ();        }    }    private Handler Handler = new Handler () {    & nbsp;   public void Handlemessage (Message msg) {             Switch (msg.what) {            case compressstatus.start:                tv.settext ("start!");                 break;            case compressstatus.handling:                 bundle B = msg.getdata ();                tv.settext (B.getint (compressstatus.percent) + "%");                 break;            case compressstatus.completed:                tv.settext ("end!");                 break;            case compressstatus.error:                 tv.settext ("error");                break;             }        };    };}

Summary: The main is to master the API and through the handler to the message, because zip4j download need to turn strong, so I will demo code and ZIP4J package of source and jar files are uploaded, there is need to download directly.

Demo, source code


Android Zip4j--Unzip the zip file and display the decompression progress in real time

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.