android unzip file

The main thing is to use streams to process large files

1. First convert the source file into the CheckedInputStream that comes with the Android system. This is a check stream:

 CheckedInputStream cis = new CheckedInputStream(new FileInputStream(srcFile), new CRC32());

2. Then convert this inspection stream into a Zip input stream:

ZipInputStream zis = new ZipInputStream(cis);

3. Get the entity of the zip stream:

while ((zipEntry = zis.getNextEntry()) != null)

4. Then use the byte output stream:

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
        int len;
        byte[] buff = new byte[DEFAULT_BUFF_SIZE];
        while ((len = zis.read(buff, 0 ,DEFAULT_BUFF_SIZE)) != -1) {
            bos.write(buff, 0, len);
        }

Full code:

 public static File decompress(File srcFile, File destFile) throws Exception {
        while (destFile.exists()) {
            destFile = new File(destFile.getAbsolutePath()+"1");
        }
        CheckedInputStream cis = new CheckedInputStream(new FileInputStream(srcFile), new CRC32());
        ZipInputStream zis = new ZipInputStream(cis);
        doDecompress(destFile, zis);
        zis.close();
        return destFile;
    }

    private static void doDecompress(File destFile, ZipInputStream zis) throws Exception {
        ZipEntry zipEntry = null;
        while ((zipEntry = zis.getNextEntry()) != null) {
            String dir = destFile.getPath() + File.separator + zipEntry.getName();
            File dirFile = new File(dir);
            fileProber(dirFile);
            if (zipEntry.isDirectory()) {
                dirFile.mkdirs();
            } else {
                doDecompressFile(dirFile, zis);
            }
            zis.closeEntry();
        }
    }

    private static void doDecompressFile(File destFile, ZipInputStream zis) throws Exception {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
        int len;
        byte[] buff = new byte[DEFAULT_BUFF_SIZE];
        while ((len = zis.read(buff, 0 ,DEFAULT_BUFF_SIZE)) != -1) {
            bos.write(buff, 0, len);
        }
        bos.close();
    }

Guess you like

Origin blog.csdn.net/howlaa/article/details/124384800