Gzip的使用

public class GzipUtil {

    /**
     * 解压, 
     * @param is zip文件的输入流
     * @param os 输出流
     */
    public static void unzip(InputStream is, OutputStream os) {
        GZIPInputStream gis = null;
        try {
            gis = new GZIPInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            while((len = gis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeQuitely(gis);
            closeQuitely(os);
        }
    }

    public static void zip(File srcFile, File targetFile) {
        FileInputStream fis = null;
        GZIPOutputStream gos = null;
        try {
            fis = new FileInputStream(srcFile);
            gos = new GZIPOutputStream(new FileOutputStream(targetFile));
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer)) != -1) {
                gos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeQuitely(gos);
            closeQuitely(fis);
        }
    }

    public static void unzip(File srcFile, File targetFile) {
        GZIPInputStream gis = null;
        FileOutputStream fos = null;
        try {
            gis = new GZIPInputStream(new FileInputStream(srcFile));
            fos = new FileOutputStream(targetFile);
            byte[] buffer = new byte[1024];
            int len;
            while((len = gis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeQuitely(gis);
            closeQuitely(fos);
        }
    }

    public static void closeQuitely(Closeable stream) {
        if(stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用方法

解压缩

String tagetPath = "data/data/" + context.getPackageName()
                + "/antivirus.db";  //解压目录文件
        File db = new File(tagetPath);
        if (!db.exists()) {
            try {
                db.createNewFile();
                InputStream open = context.getAssets().open("antivirus.zip");//在asset的原文件
                GzipUtil.unzip(open, new FileOutputStream(tagetPath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

压缩

File srcFile=new File("src/antivirus.db");源文件
        File targetFile=new File("src/antivirus.zip");压缩目标文件
        try {
            targetFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        GzipUtil.zip(srcFile, targetFile);
原文地址:https://www.cnblogs.com/kaidi1994/p/5573117.html