下载并解压缩Zip文件中的Andr​​oid [英] Download and Extract Zip File in Android

查看:156
本文介绍了下载并解压缩Zip文件中的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序从服务器下载的zip文件,解压缩这个zip文件,将文件保存到SD卡,但问题是,如果我下载4-5 MB的zip文件并提取它,这是工作不错,但如果我下载30 -35 MB zip文件,这会给我的错误,对不起我的英语不好沟通。

下面是我的$ C $下下载和放大器;解压Zip文件: -

 公共类UnzipManager {
    私有静态字符串BASE_FOLDER;

    公共静态语境localContext;
    公共静态字符串passurl;
    公共静态诠释计数;
    公共静态上下文的背景下;
    / *
     *您可以使用此标志,检查是否Unzippingthread仍在运行..
     * /
    公共静态布尔isDownloadInProgress;
    / *
     *使用此标志解压缩后,您可以检查是否有低内存
     *发生异常或not..and警告用户相应..
     * /
    公共静态布尔isLowOnMemory;
    公共静态INT I = 0;

    公共静态的ZipEntry ZipEntry的;

    公共静态无效startUnzipping(上下文CTX,诠释三,字符串URL){
        上下文= CTX;
        数= C;
        / *
         *确保localContext变量已经被初始化之前
         *调用此方法。
         *
         *另外,还要确保您已设置互联网和网络访问状态
         *应用程序的清单文件的权限。
         * /
        Log.d(调试,以startUnzipping());
        UnzipManager.BASE_FOLDER = Environment.getExternalStorageDirectory()
                +文件分割符+样本;
        / *
         *
         * /

        Log.d(调试,BASE_FOLDER:+ UnzipManager.BASE_FOLDER);
        UnzipManager.isLowOnMemory = FALSE;
        //开始解压在一个thread..which更安全
        //这样做成本高,工艺..
        passurl =网址;
        新UnzipThread()启动();
    }

    私有静态类UnzipThread继承Thread {
        @覆盖
        公共无效的run(){
            UnzipManager.isDownloadInProgress = TRUE;
            Log.d(调试,解压缩----------------------------);
            URLConnection的URLConnection的;
            尝试 {
                / *********
                 *
                 *如果你是在解压缩某些URL的压缩文件保存
                 *远程服务器
                 * ************ /
                URL finalUrl =新的URL(passurl
                / *其中的压缩文件存储的URL字符串... * /);
                的URLConnection = finalUrl.openConnection();

                //获取(压缩文件的)的InputStream从大小
                // 服务器..
                INT CONTENTLENGTH = urlConnection.getContentLength();
                Log.d(调试,urlConnection.getContentLength():
                        + CONTENTLENGTH);
                / ******************* ****
                 *
                 *你可以得到一个压缩文件从Assets文件夹输入流
                 *以及..,那还不如传递INPUTSTEAM OVER
                 *这里...让的确保您已设置STREAM内容长度
                 * 相同..
                 *
                 ************************************************** **** /
                ZipInputStream zipInputStream =新ZipInputStream(
                        urlConnection.getInputStream());
                / *
                 *遍历所有的文件和文件夹
                 * /
                对于(ZipEntry的= zipInputStream.getNextEntry();!ZipEntry的= NULL;的ZipEntry = zipInputStream
                        .getNextEntry()){
                    Log.d(调试,提取+ zipEntry.getName()+...);

                    / *
                     *提取的文件会被保存相同的文件名,在
                     *压缩文件夹。
                     * /


                    字符串innerFileName = BASE_FOLDER +文件分割符
                            + zipEntry.getName();
                    文件innerFile =新的文件(innerFileName);

                    / *
                     *检查pre-存在的文件,并采取
                     *必要的行动
                     * /
                    如果(innerFile.exists()){
                        Log.d(调试,
                                该条目已经存在!所以删除。);
                        innerFile.delete();
                    }

                    / *
                     *检查的文件夹type..and回吐提取项
                     *必要的行动
                     * /
                    如果(zipEntry.isDirectory()){
                        Log.d(调试,该条目是一个目录。);
                        innerFile.mkdirs();
                    } 其他 {
                        Log.d(调试,该条目是一个文件。);
                        FileOutputStream中的OutputStream =新的FileOutputStream(
                                innerFileName);
                        最终诠释BUFFER_SIZE = 2048;

                        / *
                         *获取缓冲的输出流..
                         * /
                        的BufferedOutputStream的BufferedOutputStream =新的BufferedOutputStream(
                                的OutputStream,BUFFER_SIZE);
                        / *
                         *写入到文件的缓冲输出流,..
                         * /
                        诠释计数= 0;
                        byte []的缓冲区=新的字节[BUFFER_SIZE];
                        而((数量= zipInputStream.read(缓冲,0,
                                BUFFER_SIZE))!=  -  1){
                            bufferedOutputStream.write(缓冲,0,计数);
                        }
                        / ************
                         *如果你想跟踪NO下载的文件,均有
                         *静态计数器变量,初始化它IN
                         * startUnzipping()调用startUnZipping()面前,
                         *增加计数器可变的HERE..LATER YOU
                         *可以使用值计数器变量的交叉校验
                         *是否所有压缩文件解压缩PROPERLY并保存
                         * 或不。
                         *
                         * **********
                         * /
                        / *
                         *输出流的句柄收..
                         * /
                        bufferedOutputStream.flush();
                        bufferedOutputStream.close();
                    }
                    / *
                     *完成当前的ZipEntry
                     * /
                    zipInputStream.closeEntry();
                }
                / *
                 *输入流的句柄收盘...
                 * /
                zipInputStream.close();
                Log.d(调试,--------------------------------);
                Log.d(调试,解压缩完成..);
                I = 1;

            }赶上(IOException异常E){
                Log.d(调试,异常发生:+ e.getMessage());
                如果(e.getMessage()。equalsIgnoreCase(设备上没有剩余空间)){
                    UnzipManager.isLowOnMemory = TRUE;
                }
                e.printStackTrace();
            }

            MainActivity.pd.dismiss();

            ((MainActivity)上下文).finish();

            UnzipManager.isDownloadInProgress = FALSE;
        }
    };
}
 

logcat的错误是: -

 十二月2号至17日:21:16.835:D / DEBUG(20562):异常发生:/mnt/sdcard/samples/iPhone_zendura_Q4a/0.png(没有这样的文件或目录)
十二月2号至17日:21:16.835:W / System.err的(20562):java.io.FileNotFoundException:/mnt/sdcard/samples/iPhone_zendura_Q4a/0.png(没有这样的文件或目录)
十二月2号至17日:21:16.906:W / System.err的(20562):在org.apache.harmony.luni.platform.OSFileSystem.open(本机方法)
十二月2号至17日:21:16.906:W / System.err的(20562):在dalvik.system.BlockGuard $ WrappedFileSystem.open(BlockGuard.java:232)
十二月2号至17日:21:16.906:W / System.err的(20562):在java.io.FileOutputStream中的< INIT>(FileOutputStream.java:94)
十二月2号至17日:21:16.906:W / System.err的(20562):在java.io.FileOutputStream中的< INIT>(FileOutputStream.java:165)
十二月2号至17日:21:16.906:W / System.err的(20562):在java.io.FileOutputStream中的< INIT>(FileOutputStream.java:144)
十二月2号至17日:21:16.906:W / System.err的(20562):在com.android.screens.UnzipManager $ UnzipThread.run(UnzipManager.java:129)
 

解决方案

解压文件

下载Zip文件

My application is downloading zip file from the server and extract this zip file and save files into sd card but problem is if i am downloading 4-5 MB zip files and extract it, this is working good but if i am downloading 30-35 MB zip file this will give me error, sorry for my bad English communication.

The Below is my Code for Download & Unzip Zip File:-

public class UnzipManager {
    private static String BASE_FOLDER;

    public static Context localContext;
    public static String passurl;
    public static int count;
    public static Context context;
    /*
     * You can use this flag to check whether Unzippingthread is still running..
     */
    public static boolean isDownloadInProgress;
    /*
     * After unzipping using this flag ,you can check whether any low memory
     * exceptions Occurred or not..and alert user accordingly..
     */
    public static boolean isLowOnMemory;
    public static int i = 0;

    public static ZipEntry zipEntry;

    public static void startUnzipping(Context ctx, int c, String url) {
        context = ctx;
        count = c;
        /*
         * MAKE SURE THAT localContext VARIABLE HAS BEEN INITIALIZED BEFORE
         * INVOKING THIS METHOD.
         * 
         * ALSO MAKE SURE YOU HAVE SET "INTERNET" AND "NETWORK ACCESS STATE"
         * PERMISSIONS IN APPLICATION'S MANIFEST FILE.
         */
        Log.d("DEBUG", "In startUnzipping()");
        UnzipManager.BASE_FOLDER = Environment.getExternalStorageDirectory()
                + File.separator + "samples";
        /*
         *
         */

        Log.d("DEBUG", "BASE_FOLDER:" + UnzipManager.BASE_FOLDER);
        UnzipManager.isLowOnMemory = false;
        // Start unzipping in a thread..which is safer
        // way to do high cost processes..
        passurl = url;
        new UnzipThread().start();
    }

    private static class UnzipThread extends Thread {
        @Override
        public void run() {
            UnzipManager.isDownloadInProgress = true;
            Log.d("DEBUG", "Unzipping----------------------------");
            URLConnection urlConnection;
            try {
                /************************************************
                 * 
                 * IF you are unzipping a zipped file save under some URL in
                 * remote server
                 * **********************************************/
                URL finalUrl = new URL(passurl
                /* Url string where the zipped file is stored... */);
                urlConnection = finalUrl.openConnection();

                // Get the size of the ( zipped file's) inputstream from
                // server..
                int contentLength = urlConnection.getContentLength();
                Log.d("DEBUG", "urlConnection.getContentLength():"
                        + contentLength);
                /*****************************************************
                 * 
                 * YOU CAN GET INPUT STREAM OF A ZIPPED FILE FROM ASSETS FOLDER
                 * AS WELL..,IN THAT CASE JUST PASS THAT INPUTSTEAM OVER
                 * HERE...MAKE SURE YOU HAVE SET STREAM CONTENT LENGTH OF THE
                 * SAME..
                 * 
                 ******************************************************/
                ZipInputStream zipInputStream = new ZipInputStream(
                        urlConnection.getInputStream());
                /*
                 * Iterate over all the files and folders
                 */
                for (zipEntry = zipInputStream.getNextEntry(); zipEntry != null; zipEntry = zipInputStream
                        .getNextEntry()) {
                    Log.d("DEBUG", "Extracting: " + zipEntry.getName() + "...");

                    /*
                     * Extracted file will be saved with same file name that in
                     * zipped folder.
                     */


                    String innerFileName = BASE_FOLDER + File.separator
                            + zipEntry.getName();
                    File innerFile = new File(innerFileName);

                    /*
                     * Checking for pre-existence of the file and taking
                     * necessary actions
                     */
                    if (innerFile.exists()) {
                        Log.d("DEBUG",
                                "The Entry already exits!, so deleting..");
                        innerFile.delete();
                    }

                    /*
                     * Checking for extracted entry for folder type..and taking
                     * necessary actions
                     */
                    if (zipEntry.isDirectory()) {
                        Log.d("DEBUG", "The Entry is a directory..");
                        innerFile.mkdirs();
                    } else {
                        Log.d("DEBUG", "The Entry is a file..");
                        FileOutputStream outputStream = new FileOutputStream(
                                innerFileName);
                        final int BUFFER_SIZE = 2048;

                        /*
                         * Get the buffered output stream..
                         */
                        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                                outputStream, BUFFER_SIZE);
                        /*
                         * Write into the file's buffered output stream ,..
                         */
                        int count = 0;
                        byte[] buffer = new byte[BUFFER_SIZE];
                        while ((count = zipInputStream.read(buffer, 0,
                                BUFFER_SIZE)) != -1) {
                            bufferedOutputStream.write(buffer, 0, count);
                        }
                        /***********************************************
                         * IF YOU WANT TO TRACK NO OF FILES DOWNLOADED, HAVE A
                         * STATIC COUNTER VARIABLE, INITIALIZE IT IN
                         * startUnzipping() before calling startUnZipping(), AND
                         * INCREMENT THE COUNTER VARIABLE OVER HERE..LATER YOU
                         * CAN USE VALUE OF COUNTER VARIABLE TO CROSS VERIFY
                         * WHETHER ALL ZIPPED FILES PROPERLY UNZIPPED AND SAVED
                         * OR NOT.
                         * 
                         * ************************************************
                         */
                        /*
                         * Handle closing of output streams..
                         */
                        bufferedOutputStream.flush();
                        bufferedOutputStream.close();
                    }
                    /*
                     * Finish the current zipEntry
                     */
                    zipInputStream.closeEntry();
                }
                /*
                 * Handle closing of input stream...
                 */
                zipInputStream.close();
                Log.d("DEBUG", "--------------------------------");
                Log.d("DEBUG", "Unzipping completed..");
                i = 1;

            } catch (IOException e) {
                Log.d("DEBUG", "Exception occured: " + e.getMessage());
                if (e.getMessage().equalsIgnoreCase("No space left on device")) {
                    UnzipManager.isLowOnMemory = true;
                }
                e.printStackTrace();
            }

            MainActivity.pd.dismiss();

            ((MainActivity)context).finish();       

            UnzipManager.isDownloadInProgress = false;
        }
    };
}

Logcat Error is:-

02-17 12:21:16.835: D/DEBUG(20562): Exception occured: /mnt/sdcard/samples/iPhone_zendura_Q4a/0.png (No such file or directory)
02-17 12:21:16.835: W/System.err(20562): java.io.FileNotFoundException: /mnt/sdcard/samples/iPhone_zendura_Q4a/0.png (No such file or directory)
02-17 12:21:16.906: W/System.err(20562):    at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
02-17 12:21:16.906: W/System.err(20562):    at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
02-17 12:21:16.906: W/System.err(20562):    at java.io.FileOutputStream.<init>(FileOutputStream.java:94)
02-17 12:21:16.906: W/System.err(20562):    at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
02-17 12:21:16.906: W/System.err(20562):    at java.io.FileOutputStream.<init>(FileOutputStream.java:144)
02-17 12:21:16.906: W/System.err(20562):    at com.android.screens.UnzipManager$UnzipThread.run(UnzipManager.java:129)

解决方案

Unzip File

Download Zip File

这篇关于下载并解压缩Zip文件中的Andr​​oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆