如何压缩和解压缩的文件?文件

2023-09-12 08:39:54 作者:女巫的扫帚

如何压缩和解压缩这些都是已经在DDMS中的文件:数据/数据​​/ mypackage中/文件/ 我需要一个简单的例子为。我已经搜索相关来压缩和解压缩。但是,可对我来说没有任何一个例子。任何人都可以讲一些实例。先谢谢了。

How to zip and unzip the files which are all already in DDMS : data/data/mypackage/files/ I need a simple example for that. I've already search related to zip and unzip. But, no one example available for me. Can anyone tell some example. Advance Thanks.

推荐答案

看看java.util.zip。*类压缩功能。我做了一些基本的压缩/解压缩code,我已经粘贴下面。希望它能帮助。

Take a look at java.util.zip.* classes for zip functionality. I've done some basic zip/unzip code, which I've pasted below. Hope it helps.

public static void zip(String[] files, String zipFile) throws IOException {
    BufferedInputStream origin = null;
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
    try { 
        byte data[] = new byte[BUFFER_SIZE];

        for (int i = 0; i < files.length; i++) {
            FileInputStream fi = new FileInputStream(files[i]);    
            origin = new BufferedInputStream(fi, BUFFER_SIZE);
            try {
                ZipEntry entry = new ZipEntry(files[i].substring(files[i].lastIndexOf("/") + 1));
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
                    out.write(data, 0, count);
                }
            }
            finally {
                origin.close();
            }
        }
    }
    finally {
        out.close();
    }
}

public static void unzip(String zipFile, String location) throws IOException {
    try {
        File f = new File(location);
        if(!f.isDirectory()) {
            f.mkdirs();
        }
        ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
        try {
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
                String path = location + ze.getName();

                if (ze.isDirectory()) {
                    File unzipFile = new File(path);
                    if(!unzipFile.isDirectory()) {
                        unzipFile.mkdirs();
                    }
                }
                else {
                    FileOutputStream fout = new FileOutputStream(path, false);
                    try {
                        for (int c = zin.read(); c != -1; c = zin.read()) {
                            fout.write(c);
                        }
                        zin.closeEntry();
                    }
                    finally {
                        fout.close();
                    }
                }
            }
        }
        finally {
            zin.close();
        }
    }
    catch (Exception e) {
        Log.e(TAG, "Unzip exception", e);
    }
}
 
精彩推荐
图片推荐