Android开发中,我们经常会遇到上传文件,用到压缩文件、文件夹的功能,今天我们主要讲解这个功能,具体的实现如下:
/*** 压缩文件和文件夹** @param srcFileString 要压缩的文件或文件夹* @param zipFileString 压缩完成的Zip路径* @throws Exception*/ public static void ZipFolder(String srcFileString, String zipFileString,String zipName) {//创建ZIPZipOutputStream outZip = null;try {//创建文件File file = new File(srcFileString);File outPath = new File(zipFileString);if (!outPath.exists()){outPath.mkdirs();}outZip = new ZipOutputStream(new FileOutputStream(new File(outPath, zipName)));//压缩ZipFiles(file.getParent() + File.separator, file.getName(), outZip);isSuccess = true;} catch (Exception e) {isSuccess = false;e.printStackTrace();} finally {//完成和关闭if (outZip != null) {try {outZip.finish();outZip.close();}catch (IOException e) {e.printStackTrace();}}} }
下面这段代码是压缩文件:
/*** 压缩文件** @param folderString* @param fileString* @param zipOutputSteam* @throws Exception*/ private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam)throws Exception {if (zipOutputSteam == null)return;FileInputStream inputStream = null;try {File file = new File(folderString + fileString);if (file.isFile()) {ZipEntry zipEntry = new ZipEntry(fileString);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 (IOException e) {e.printStackTrace();} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException ex) {ex.printStackTrace();}}} }