android 压缩文件

本篇文章主要记录下android中压缩文件的工具类.

public class ZipUtils {
    public static boolean zip(String sourceDir, String zipFile, int level) {
        if (TextUtils.isEmpty(sourceDir) || TextUtils.isEmpty(zipFile) ) {
            throw new RuntimeException("invalid arguments");
        }

        boolean ret = false;
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
            zos.setLevel(level);

            File file = new File(sourceDir);
            String sourcePath;
            if (file.isDirectory()) {
                sourcePath = file.getPath();
            } else {
                //直接压缩单个文件时,取父目录
                sourcePath = file.getParent();
            }

            byte[] buffer = new byte[4096];
            ret = doZip(file, sourcePath, zos, buffer);
            zos.closeEntry();
        } catch (Throwable e) {
            Log.e(TAG, "zip: ",e );
        } finally {
            closeQuietly(zos);
        }
        return ret;
    }

    public static void closeQuietly(Closeable c) {
        if (null != c) {
            try {
                c.close();
            } catch (Throwable e) {
                Log.e(TAG, "closeQuietly: ",e );
            }
        }
    }

    private static boolean doZip(File source, String basePath, ZipOutputStream zos, byte[] buffer) {
        File[] files;
        if (source.isDirectory()) {
            files = source.listFiles();
        } else {
            files = new File[1];
            files[0] = source;
        }

        boolean ret = true;
        int length;
        String pathName;//存相对路径(相对于待压缩的根目录)
        try {
            for (File file : files) {
                pathName = file.getPath().substring(basePath.length() + 1);
                if (file.isDirectory()) {
                    pathName = pathName + "/";
                    zos.putNextEntry(new ZipEntry(pathName));
                    if (!doZip(file, basePath, zos, buffer)) break;
                } else {
                    InputStream is = null;
                    try {
                        is = new FileInputStream(file);
                        BufferedInputStream bis = new BufferedInputStream(is);
                        zos.putNextEntry(new ZipEntry(pathName));
                        while ((length = bis.read(buffer)) > 0) {
                            zos.write(buffer, 0, length);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                        ret = false;
                        break;
                    } finally {
                        closeQuietly(is);
                    }
                }
            }
        } catch (Throwable e) {
            Log.e(TAG, "doZip: ",e );
            ret = false;
        }
        return ret;
    }
}

调用程序:

ZipUtils.zip("sdcard/test","sdcard/test2.zip",9);

你可能感兴趣的:(android,android)