android 壓縮文件或者文件夾為zip格式 代碼

壓縮文件用的,,,

public class ZipUtil
{

public static void zipFolder(String
srcFilePath, String zipFilePath) throws Exception {

// 創建Zip包

java.util.zip.ZipOutputStream outZip = new java.util.zip.ZipOutputStream(newjava.io.FileOutputStream(

zipFilePath));

// 打開要輸出的文件

java.io.File file = new java.io.File(srcFilePath);

// 壓縮

zipFiles(file.getParent() + java.io.File.separator, file.getName(), outZip);

// 完成,關閉

outZip.finish();

outZip.close();

}

private static void zipFiles(String
folderPath, String filePath, java.util.zip.ZipOutputStream zipOut)

throws Exception {

if (zipOut == null) {

return;

}

java.io.File file = new java.io.File(folderPath + filePath);

// 判斷是不是文件

if (file.isFile()) {

java.util.zip.ZipEntry zipEntry = new java.util.zip.ZipEntry(filePath);

java.io.FileInputStream inputStream = new java.io.FileInputStream(file);

zipOut.putNextEntry(zipEntry);

int len;

byte[] buffer = new byte[100000];

while ((len = inputStream.read(buffer)) != -1) {

zipOut.write(buffer, 0, len);

}

inputStream.close();

zipOut.closeEntry();

} else {

// 文件夾的方式,獲取文件夾下的子文件

String fileList[] = file.list();

// 如果沒有子文件, 則添加進去即可

if (fileList.length <= 0) {

java.util.zip.ZipEntry zipEntry = newjava.util.zip.ZipEntry(filePath + java.io.File.separator);

zipOut.putNextEntry(zipEntry);

zipOut.closeEntry();

}

// 如果有子文件, 遍歷子文件

for (int i = 0; i < fileList.length;
i++) {

zipFiles(folderPath, filePath + java.io.File.separator + fileList[i], zipOut);

}

}

}

}

發佈留言