programmer
programmer

Reputation: 13

Unzip Folder in Android

I try to make an app that show 100 pictures. I want to zip folder of photos and then put it on my project. now i need to understand How can copy a zip folder to internal storage,And then unzip it in android?

Upvotes: 1

Views: 2326

Answers (1)

Jose Rodriguez
Jose Rodriguez

Reputation: 10152

You can include your .zip file on Assets folder of apk, and them on code, copy the .zip to internal storage and unzipping using a ZipInputStream.

First copy de .zip file to internal storage, and after unzip a file:

    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);
        }
    }

Upvotes: 3

Related Questions