Android开发中压缩文件和文件夹
2023-12-14 12:31:12
Android开发中,我们经常会遇到上传文件,用到压缩文件、文件夹的功能,今天我们主要讲解这个功能,具体的实现如下:
/** * 压缩文件和文件夹 * * @param srcFileString 要压缩的文件或文件夹 * @param zipFileString 压缩完成的Zip路径 * @throws Exception */ public static void ZipFolder(String srcFileString, String zipFileString,String zipName) { //创建ZIP ZipOutputStream 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(); } } } }
文章来源:https://blog.csdn.net/qq_36451275/article/details/134991881
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!