Download and decompress the Zip file based on Android, and update the simple help class of the UI

Source: Internet
Author: User

Download and decompress the Zip file based on Android, and update the simple help class of the UI

 

Download file:

/ * *
* download file
*
* @ param down_url
* @ param output
* @ param tmpDir
* /
Private void download(String down_url, File output, File tmpDir)
{
InputStream InputStream = null;
OutputStream OutputStream = null;
The File TMP = null;

Int down_step = 1; / / hint step
Int totalSize = 0;
Int downloadCount = 0; // the size has been downloaded
Int updateCount = 0; // size of file already uploaded

The try
{
TMP = file.createtempfile (download,.tmp, tmpDir);

URL URL = new URL(down_url);
HttpURLConnection HttpURLConnection = (HttpURLConnection) url
The openConnection ();
HttpURLConnection. SetConnectTimeout (30 * 1000);
HttpURLConnection. SetReadTimeout (30 * 1000);
// gets the size of the downloaded file
TotalSize = httpURLConnection. GetContentLength ();

InputStream = new URL (down_url). OpenStream ();
OutputStream = new BufferedOutputStream(new FileOutputStream(TMP));

Byte [] buffer = new byte[BUFFER_SIZE];
Int readsize = 0;

While ((readsize = inputstream.read (buffer))! = 1)
{
OutputStream. Write (buffer, 0, readsize);
DownloadCount + = readsize; // get the size downloaded from time to time
// each increase is 1%
If (updateCount = = 0
|| (downloadCount * 100 / totalSize - down_step) >= updateCount)
{
UpdateCount + = down_step;

SendMessage (DOWN_UPDATA updateCount);
}
}

If (httpURLConnection! = null)
{
HttpURLConnection. Disconnect ();
}
TMP. RenameTo (output);
TMP = null;
} the catch (IOException e)
{
SendMessage (DOWN_ERROR, 0);
Throw new RuntimeException (e);
} the finally
{
The try
{
If (TMP! = null)
{
TMP. The delete ();
TMP = null;
}
If (inputStream! = null)
{
InputStream. Close ();
InputStream = null;
}
If (outputStream! = null)
{
OutputStream. Close ();
OutputStream = null;
}
} the catch (Exception e2)
{
SendMessage (DOWN_ERROR, 0);
}

SendMessage (DOWN_FINISH, 0);
}
}

Decompress the Zip file

public class ZipUnPack {
    private static final int BUFFER_SIZE = 8192;

    private String _zipFile;
    private String _location;
    private byte[] _buffer;

    /**
     * Constructor.
     * 
     * @param zipFile
     *            Fully-qualified path to .zip file
     * @param location
     *            Fully-qualified path to folder where files should be written.
     *            Path must have a trailing slash.
     */
    public ZipUnPack(String zipFile, String location) {
        _zipFile = zipFile;
        _location = location;
        _buffer = new byte[BUFFER_SIZE];
        dirChecker();
    }


    public Boolean unzip() {
        FileInputStream fin = null;
        ZipInputStream zin = null;
        OutputStream fout = null;

        File outputDir = new File(_location);
        File tmp = null;

        Boolean isSucess = true;
        try {
            fin = new FileInputStream(_zipFile);
            zin = new ZipInputStream(fin);
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
                Log.d(Decompress, Unzipping  + ze.getName());

                if (ze.isDirectory()) {
                    dirChecker(ze.getName());
                } else {
                    tmp = File.createTempFile(decomp, .tmp, outputDir);
                    fout = new BufferedOutputStream(new FileOutputStream(tmp));
                    copyStream(zin, fout, _buffer, BUFFER_SIZE);
                    zin.closeEntry();
                    fout.close();
                    fout = null;
                    tmp.renameTo(new File(_location + ze.getName()));
                    tmp = null;
                }
            }
            zin.close();
            zin = null;
        } catch (IOException e) {
            isSucess = false;
            throw new RuntimeException(e);
        } finally {
            if (tmp != null) {
                try {
                    tmp.delete();
                } catch (Exception ignore) {

                }
            }
            if (fout != null) {
                try {
                    fout.close();
                } catch (Exception ignore) {
                    ;
                }
            }
            if (zin != null) {
                try {
                    zin.closeEntry();
                } catch (Exception ignore) {
                    ;
                }
            }
            if (fin != null) {
                try {
                    fin.close();
                } catch (Exception ignore) {
                    ;
                }
            }

            isSucess = true;
        }

        return isSucess;
    }

    private void dirChecker(String dir) {
        File f = new File(_location + dir);

        if (!f.isDirectory()) {
            f.mkdirs();
        }
    }


    /**
     * Copy from one stream to another. Throws IOException in the event of error
     * (for example, SD card is full)
     * 
     * @param is
     *            Input stream.
     * @param os
     *            Output stream.
     * @param buffer
     *            Temporary buffer to use for copy.
     * @param bufferSize
     *            Size of temporary buffer, in bytes.
     */
    private void copyStream(InputStream is, OutputStream os,
            byte[] buffer, int bufferSize) throws IOException {
        try {
            for (;;) {
                int count = is.read(buffer, 0, bufferSize);
                if (count == -1) {
                    break;
                }
                os.write(buffer, 0, count);
            }
        } catch (IOException e) {
            throw e;
        }
    }
}

The entire help class:

Public class ZipDownLoadHelper
{

Private static final int BUFFER_SIZE = 1024;

Private static final int DOWN_BEGIN = 0;
Private static final int DOWN_UPDATA = 1;
Private static final int DOWN_FINISH = 2;
Private static final int DOWN_ERROR = 3;
Private static final int UNPACK_BEGIN = 4;
Private static final int UNPACK_END = 5;
Private static final int UNPACK_ERROR = 6;

Private Context mContext;

Private Thread mDownLoadThread;

Private OnZipDownLoadAndUnpackListener mOnZipDownLoadAndUnpackListener;

Private Handler Handler = new Handler()
{
Public void handleMessage (Message MSG)
{
If (! Thread. CurrentThread (). The isInterrupted ())
{
The switch (MSG. What)
{
Case DOWN_BEGIN:
If (mOnZipDownLoadAndUnpackListener! = null)
{
MOnZipDownLoadAndUnpackListener. OnDownLoadStart ();
}

Break;
Case DOWN_UPDATA:
Int factor = MSG. Arg1;
If (mOnZipDownLoadAndUnpackListener! = null)
{
mOnZipDownLoadAndUnpackListener
OnDownLoading (factor);
}

Break;

Case DOWN_FINISH:
If (mOnZipDownLoadAndUnpackListener! = null)
{
MOnZipDownLoadAndUnpackListener. OnDownLoadFinish ();
}

Break;
Case DOWN_ERROR:
If (mOnZipDownLoadAndUnpackListener! = null)
{
MOnZipDownLoadAndUnpackListener. OnDownLoadError ();
}

Break;
Case UNPACK_BEGIN:
If (mOnZipDownLoadAndUnpackListener! = null)
{
MOnZipDownLoadAndUnpackListener. OnZipUnpackStart ();
}
Break;
Case UNPACK_END:

If (mOnZipDownLoadAndUnpackListener! = null)
{
MOnZipDownLoadAndUnpackListener. OnZipUnpackFinish ();
}

Break;
Case UNPACK_ERROR:

Break;

Default:
Break;
}
}
};
};

Public ZipDownLoadHelper Context (Context)
{
Enclosing mContext = context;
}

/ * *
* start thread
*
* @ param url
* /
Public void startDownLoadAndZip(final String url)
{
MDownLoadThread = new Thread ()
{
@ Override
Public void the run ()
{
SendMessage (DOWN_BEGIN, 0);
// Temp folder for holding asset during download
The File zipDir = ExternalStorage. GetSDCacheDir (mContext, TMP);

// File path to store.zip File before unzipping
File zipFile = new File(zipdir.getpath () + /temp.zip);

// Folder to hold unzipped output
The File outputDir = ExternalStorage. GetSDCacheDir (mContext,
WMS);

The try
{
The download (url, zipFile, zipDir);
UnzipFile (zipFile, outputDir);
} the finally
{
ZipFile. Delete ();
}
}
};
MDownLoadThread. Start ();
}

@ SuppressWarnings (deprecation)
Public void destroyThread ()
{
MDownLoadThread. Stop ();
}

/ * *
* download file
*
* @ param down_url
* @ param output
* @ param tmpDir
* /
Private void download(String down_url, File output, File tmpDir)
{
InputStream InputStream = null;
OutputStream OutputStream = null;
The File TMP = null;

Int down_step = 1; / / hint step
Int totalSize = 0;
Int downloadCount = 0; // the size has been downloaded
Int updateCount = 0; // size of file already uploaded

The try
{
TMP = file.createtempfile (download,.tmp, tmpDir);

URL URL = new URL(down_url);
HttpURLConnection HttpURLConnection = (HttpURLConnection) url
The openConnection ();
HttpURLConnection. SetConnectTimeout (30 * 1000);
HttpURLConnection. SetReadTimeout (30 * 1000);
// gets the size of the downloaded file
TotalSize = httpURLConnection. GetContentLength ();

InputStream = new URL (down_url). OpenStream ();
OutputStream = new BufferedOutputStream(new FileOutputStream(TMP));

Byte [] buffer = new byte[BUFFER_SIZE];
Int readsize = 0;
While ((readsize = inputstream.read (buffer))! = 1)
{
OutputStream. Write (buffer, 0, readsize);
DownloadCount + = readsize; // get the size downloaded from time to time
// each increase is 1%
If (updateCount = = 0
|| (downloadCount * 100 / totalSize - down_step) >= updateCount)
{
UpdateCount + = down_step;

SendMessage (DOWN_UPDATA updateCount);
}
}

If (httpURLConnection! = null)
{
HttpURLConnection. Disconnect ();
}
TMP. RenameTo (output);
TMP = null;
} the catch (IOException e)
{
SendMessage (DOWN_ERROR, 0);
Throw new RuntimeException (e);
} the finally
{
The try
{
If (TMP! = null)
{
TMP. The delete ();
TMP = null;
}
If (inputStream! = null)
{
InputStream. Close ();
InputStream = null;
}
If (outputStream! = null)
{
OutputStream. Close ();
OutputStream = null;
}
} the catch (Exception e2)
{
SendMessage (DOWN_ERROR, 0);
}

SendMessage (DOWN_FINISH, 0);
}
}

Private void sendMessage(int flag, int factor)
{
Message MSG = new Message();
The switch (flag)
{

Case DOWN_BEGIN :// start
Case DOWN_FINISH :// finished
Case DOWN_ERROR :// failure
Case UNPACK_BEGIN:
Case UNPACK_END:
Case UNPACK_ERROR:

Break;
Case DOWN_UPDATA :// update the progress bar
MSG. Arg1 = factor;
Break;

Default:
Break;
}
MSG. What = flag;
Handler. SendMessage (MSG);
}

/ * *
* unzip the file
*
* @ param zipFile
* @ param destination
* /
Private void unzipFile(File zipFile, File destination)
{
SendMessage (UNPACK_BEGIN, 0);
ZipUnPack decomp = new ZipUnPack(zipfile.getpath (),
Destination. GetPath () + File. The separator);
Boolean isOk = decomp. Unzip ();
If (! IsOk)
{
SendMessage (UNPACK_ERROR, 0);
}
The else
{
SendMessage (UNPACK_END, 0);
}

}

/ * *
* bind monitor
*
* @ param listener
* /
Public void setOnZipDownLoadAndUnpackListener (
OnZipDownLoadAndUnpackListener listener)
{
Enclosing mOnZipDownLoadAndUnpackListener = listener;
}

Public interface OnZipDownLoadAndUnpackListener
{

/ * *
* download begins
* /
Public void onDownLoadStart ();

/ * *
* download updates
*
* @ param factor
* /
Public void onDownLoading (int factor);

/ * *
* download failed
* /
Public void onDownLoadError ();

/ * *
* download completed
* /
Public void onDownLoadFinish ();

/ * *
* decompression begins
* /
Public void onZipUnpackStart ();

/ * *
* unzip failed
* /
Public void onZipUnpackError ();

/ * *
* decompression completed
* /
Public void onZipUnpackFinish ();
}

}

If you have not checked it carefully, there may be bugs. If you are using a partner, debug it and notify me. Thank you.

 


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.