Android 将文件压缩成ZIP
核心API: ZipOutputStream
public static void ZipFolder(String srcFileString, String zipFileString) {
//创建ZIP
try {
ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(new File(zipFileString + "" + System.currentTimeMillis() + ".zip")));
//创建文件
File file = new File(srcFileString);
//压缩
ZipFiles(file.getParent() + File.separator, file.getName(), outZip);
//完成和关闭
outZip.finish();
outZip.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) {
try {
if (zipOutputSteam == null)
return;
File file = new File(folderString + fileString);
if (file.isFile()) {
ZipEntry zipEntry = new ZipEntry(fileString);
FileInputStream inputStream = new FileInputStream(file);
zipOutputSteam.putNextEntry(zipEntry);
int len;
byte[] buffer = new byte[4096];
while ((len = inputStream.read(buffer)) != -1) {
zipOutputSteam.write(buffer, 0, len);
}
zipOutputSteam.closeEntry();
} else {
//文件夹
String fileList[] = file.list();
//没有子文件和压缩
if (fileList.length <= 0) {
ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
zipOutputSteam.putNextEntry(zipEntry);
zipOutputSteam.closeEntry();
}
//子文件和递归
for (int i = 0; i < fileList.length; i++) {
ZipFiles(folderString + fileString + "/", fileList[i], zipOutputSteam);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
网友评论