Android从内部存储解压缩zip文件

时间:2017-05-01 05:51:30

标签: android storage unzip internal

我正在从服务器下载zip文件到内部存储。下载后我想在内部存储本身解压缩该文件。我的文件被下载到内部存储器,我可以看到,但解压缩时我无法读取它。下面是我的unzipfile()方法。谁能告诉我哪里出错?

public void unzipfile()
    {
        try {

            Log.d("unzipiing","unzipping");
            ContextWrapper cw = new ContextWrapper(context);
            String name_="foldername"; //Folder name in device android/data/
            File directory = cw.getDir(name_, Context.MODE_PRIVATE);
            File mypath=new File(directory,"dwnld");

            FileOutputStream fout = new FileOutputStream(mypath);

            File yourFile = new File(directory,"dwnld.zip");
            Log.d("unzipiing","filepath -" + yourFile.getPath());

            FileInputStream fin = new FileInputStream(yourFile.getPath());
            ZipInputStream zin = new ZipInputStream(fin);
            Log.d("unzipiing","zin size -" + zin.available());
           // zin.available() give -1 in console log

            BufferedInputStream in = new BufferedInputStream(zin);
            BufferedOutputStream out = new BufferedOutputStream(fout);


        byte b[] = new byte[zin.available()];
        int n;
            Log.d("unzip","n - " + in.read(b,0,1024));
        while ((n = in.read(b,0,1024)) >= 0) {
            out.write(b,0,n);
            Log.d("unzip byte"," - " + n);
        }

        out.flush();
        out.close();
            in.close();
            fin.close();
            zin.close();
        }
        catch (Exception e){
        }
    }

1 个答案:

答案 0 :(得分:0)

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

使用此方法进行解压缩

 public void unzip(String _zipFile, String _targetLocation) {

            //create target location folder if not exist
            dirChecker(_targetLocatioan);

            try {
                FileInputStream fin = new FileInputStream(_zipFile);
                ZipInputStream zin = new ZipInputStream(fin);
                ZipEntry ze = null;
                while ((ze = zin.getNextEntry()) != null) {

                    //create dir if required while unzipping
                    if (ze.isDirectory()) {
                        dirChecker(ze.getName());
                    } else {
                        FileOutputStream fout = new FileOutputStream(_targetLocation + ze.getName());
                        for (int c = zin.read(); c != -1; c = zin.read()) {
                            fout.write(c);
                        }

                        zin.closeEntry();
                        fout.close();
                    }

                }
                zin.close();
            } catch (Exception e) {
                System.out.println(e);
            }
    }

检查路径

public void dirChecker(String filepath)
{
File file = new File(filePath);
if(file.exists())      
//Do something
else
// Do something else.
}