Home > Java > javaTutorial > How to Unzip Files from a ZIP Archive in Android?

How to Unzip Files from a ZIP Archive in Android?

Barbara Streisand
Release: 2024-10-29 13:16:29
Original
1075 people have browsed it

How to Unzip Files from a ZIP Archive in Android?

Extracting Files from ZIP Archives in Android

Unzipping files programmatically in Android enables the manipulation and retrieval of individual files from a compressed ZIP archive. To achieve this, developers utilize the ZipInputStream class, which provides an efficient and convenient way to extract files.

Consider the following code snippet that effectively unzips files from a specified ZIP archive:

<code class="java">private boolean unpackZip(String path, String zipname) {
    InputStream is;
    ZipInputStream zis;
    try {
        String filename;
        is = new FileInputStream(path + zipname);
        zis = new ZipInputStream(new BufferedInputStream(is));

        ZipEntry ze;
        byte[] buffer = new byte[1024];
        int count;

        while ((ze = zis.getNextEntry()) != null) {
            filename = ze.getName();

            // Create directories if necessary
            if (ze.isDirectory()) {
                File fmd = new File(path + filename);
                fmd.mkdirs();
                continue;
            }

            FileOutputStream fout = new FileOutputStream(path + filename);

            while ((count = zis.read(buffer)) != -1) {
                fout.write(buffer, 0, count);
            }

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

        zis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}</code>
Copy after login

This code initializes an input stream for the specified ZIP archive and creates a ZipInputStream object to process the compressed data. It then iterates through the ZIP entries, extracting files accordingly. If an entry is a directory, the code creates the necessary directories; otherwise, it writes the extracted data to a file with the same name and location as in the ZIP archive.

By utilizing this code snippet, developers can efficiently unpack ZIP archives in Android applications, providing access to individual files within the archive.

The above is the detailed content of How to Unzip Files from a ZIP Archive in Android?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template