Android zip 解压
本文主要记录下android中对zip文件的解压操作.
代码如下:
public class ZipUtils {
/**
* 解压文件
*
* @throws
*/
public static void unZip(String zipFilePath, File targetDir) throws IOException {
File destDir = new File(targetDir);
if (!destDir.exists()) {
destDir.mkdir();
}
File file = new File(zipFilePath);
FileInputStream fis = new FileInputStream(file);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
String targetBasePath = targetDir.getAbsolutePath();
unzip(zis, targetBasePath);
}
private static void unzip(ZipInputStream zis, String targetPath) throws IOException {
ZipEntry entry = zis.getNextEntry();
if (entry != null) {
String entryName = entry.getName();
File file = new File(targetPath + File.separator + entry.getName());
if (entry.isDirectory()) {
// 可能存在空文件夹
if (!file.exists()) {
file.mkdirs();
}
unzip(zis, targetPath);
} else {
File parentFile = file.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);// 输出流创建文件时必须保证父路径存在
int len = 0;
byte[] buf = new byte[1024];
while ((len = zis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
}catch (Exception ex)
{}
finally {
if(fos != null)
{
fos.close();
}
}
zis.closeEntry();
unzip(zis, targetPath);
}
}
}
}