在Android中解压缩文件夹

时间:2014-08-30 19:17:25

标签: android unzip

我尝试制作一张显示100张照片的应用。 我想压缩照片文件夹,然后把它放在我的项目上。 现在我需要了解如何将zip文件夹复制到内部存储,然后在android中解压缩?

1 个答案:

答案 0 :(得分:3)

您可以将.zip文件包含在apk的Assets文件夹中,将它们包含在代码中,将.zip复制到内部存储并使用ZipInputStream解压缩。

首先将de .zip文件复制到内部存储,然后解压缩文件:

    protected void copyFromAssetsToInternalStorage(String filename){
        AssetManager assetManager = getAssets();

        try {
            InputStream input = assetManager.open(filename);
            OutputStream output = openFileOutput(filename, Context.MODE_PRIVATE);

             copyFile(input, output);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void unZipFile(String filename){
        try {
            ZipInputStream zipInputStream = new ZipInputStream(openFileInput(filename));
            ZipEntry zipEntry;

            while((zipEntry = zipInputStream.getNextEntry()) != null){
                FileOutputStream zipOutputStream = openFileOutput(zipEntry.getName(), MODE_PRIVATE);

                int length;
                byte[] buffer = new byte[1024];

                while((length = zipInputStream.read(buffer)) > 0){
                    zipOutputStream.write(buffer, 0, length);
                }

                zipOutputStream.close();
                zipInputStream.closeEntry();
            }
            zipInputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
            out.write(buffer, 0, read);
        }
    }