天天看点

android zip怎么压缩,android自带zip轻松实现压缩解压

android自带zip轻松实现压缩解压

开发过程用到了zip压缩包,写了一个工具类,该类可以实现把字符串直接压缩成zip格式,省去了写入文件再压缩的步骤:

public class ZipUtil {

public static void compress(String str,String path) throws IOException {

if (null == str || str.length() <= 0) {

return;

}

FileOutputStream fileOutputStream = new FileOutputStream(path);

GZIPOutputStream gzip = new GZIPOutputStream(fileOutputStream);

gzip.write(str.getBytes("utf-8"));

gzip.close( );

fileOutputStream.close();

}

public static String unCompress(Context context,String path) {

try {

File file = new File(path);

if (!file.exists()) {

return context.getResources().getString(R.string.FileNotExits);

}

ByteArrayOutputStream out = new ByteArrayOutputStream();

// 创建一个新的输出流

FileInputStream fileInputStream = new FileInputStream(path);

GZIPInputStream gzip = new GZIPInputStream(fileInputStream);

byte[] buffer = new byte[256];

int n = 0;

// 将未压缩数据读入字节数组

while ((n = gzip.read(buffer)) >= 0) {

out.write(buffer, 0, n);

}

return out.toString("utf-8");

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

http://www.dengb.com/Androidjc/872012.htmlwww.dengb.comtruehttp://www.dengb.com/Androidjc/872012.htmlTechArticleandroid自带zip轻松实现压缩解压 开发过程用到了zip压缩包,写了一个工具类,该类可以实现把字符串直接压缩成zip式,省去了写入文件再压...