最近有一个需求,要把数据以zip格式的压缩文件下载到缓存中的需. 在网上看了很多代码 没有现成可用的 所以就自己写了一段,发现代码不多但这里面坑还是不少的, 已经亲测通过没有问题, 大家也可以稍作修改, 也欢迎大家指教.
public class ZipUtil {
/**
* 从assets中解压zip文件的方法
*
* @param zipName 压缩文件的名称
* @param targetPath 解压的路径
*/
public static void unzipFileFromAssets(String zipName, String targetPath) {
try {
int bufferSize = 1024 * 10;
// 建立zip输入流
ZipInputStream zipInputStream = new ZipInputStream(APP.context.getAssets().open(zipName));
// 每一个zip文件的实例对象
ZipEntry zipEntry;
// 文件路径名称
String fileName = "";
// 从输入流中得到实例
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
fileName = zipEntry.getName();
//如果为文件夹,则在目标目录创建文件夹
if (zipEntry.isDirectory()) {
// 截取字符串,去掉末尾的分隔符
fileName = fileName.substring(0, fileName.length() - 1);
// 创建文件夹
File folder = new File(targetPath + File.separator + fileName);
if (!folder.exists()) {
folder.mkdirs();
Log.i("ZipUtils", "unzip mkdirs : " + folder.getAbsolutePath());
}
} else {
File file = new File(targetPath + File.separator + fileName);
if (!file.exists()) {
file.createNewFile();
// 得到目标路径的输出流
FileOutputStream fos = new FileOutputStream(file);
// 开始读写数据
int length = 0;
byte[] buffer = new byte[bufferSize];
while ((length = zipInputStream.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
Log.i("ZipUtils", "unzip createNewFile : " + file.getAbsolutePath());
}
}
}
zipInputStream.close();
if(new File(zipName).delete()) Log.i("ZipUtils","zipFile has been deleted");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从assets中获取文件到缓存目录
*
* @param context 上下文对象
* @param fileName 文件的名称
*/
public static void copyFileFromAssetsToCache(Context context, String fileName) {
try {
File targetFile = new File(context.getCacheDir() + File.separator + fileName);
if (targetFile.exists()) {
Log.i("ZipUtil", "file is existing : " + targetFile.getAbsolutePath());
return;
} else {
InputStream is = context.getAssets().open(fileName);
FileOutputStream fos = new FileOutputStream(targetFile);
int i = 0;
byte[] buffer = new byte[1024 * 10];
while ((i = is.read()) != -1) {
fos.write(buffer, 0, i);
}
is.close();
fos.close();
Log.i("ZipUtil", "copy success : " + targetFile.getAbsolutePath());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}