如何在Codename One中使用zipme压缩文件?求实现示例代码
Codename One 中使用 ZipSupport(zipme)实现文件压缩的实现方案
ZipSupport 扩展原生支持zip压缩能力,可直接使用库内提供的ZipOutputStream完成压缩操作,以下是可直接复用的实现代码:
- 前置准备:在Codename One项目的扩展管理面板中勾选启用ZipSupport扩展即可,无需额外手动导入依赖。
- 支持场景:单文件压缩、多文件批量压缩、多层级目录递归压缩,自动保留原有目录结构。
import com.codename1.io.zip.ZipEntry; import com.codename1.io.zip.ZipOutputStream; import com.codename1.io.FileSystemStorage; import com.codename1.io.Util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * 通用压缩方法 * @param sourcePath 待压缩的文件/目录绝对路径 * @param targetZipPath 生成的zip文件保存绝对路径 * @throws IOException 读写过程中出现的IO异常 */ public void compressToZip(String sourcePath, String targetZipPath) throws IOException { FileSystemStorage storage = FileSystemStorage.getInstance(); try (OutputStream fileOut = storage.openOutputStream(targetZipPath); ZipOutputStream zipOut = new ZipOutputStream(fileOut)) { if (storage.isDirectory(sourcePath)) { // 递归处理目录 writeDirectoryToZip(zipOut, sourcePath, ""); } else { // 处理单个文件 writeSingleFileToZip(zipOut, sourcePath, storage.getFileName(sourcePath)); } zipOut.finish(); } } /** * 递归写入目录内容到zip流 */ private void writeDirectoryToZip(ZipOutputStream zipOut, String currentDirPath, String parentEntryPath) throws IOException { FileSystemStorage storage = FileSystemStorage.getInstance(); String[] childEntries = storage.listFiles(currentDirPath); if (childEntries == null) { return; } for (String childName : childEntries) { String fullChildPath = currentDirPath + (currentDirPath.endsWith("/") ? "" : "/") + childName; String currentEntryPath = parentEntryPath.isEmpty() ? childName : parentEntryPath + "/" + childName; if (storage.isDirectory(fullChildPath)) { // 写入目录条目,保证空目录可被正常识别 zipOut.putNextEntry(new ZipEntry(currentEntryPath + "/")); zipOut.closeEntry(); // 递归处理子目录 writeDirectoryToZip(zipOut, fullChildPath, currentEntryPath); } else { writeSingleFileToZip(zipOut, fullChildPath, currentEntryPath); } } } /** * 写入单个文件到zip流 */ private void writeSingleFileToZip(ZipOutputStream zipOut, String filePath, String entryName) throws IOException { FileSystemStorage storage = FileSystemStorage.getInstance(); try (InputStream fileIn = storage.openInputStream(filePath)) { ZipEntry entry = new ZipEntry(entryName); zipOut.putNextEntry(entry); Util.copy(fileIn, zipOut); zipOut.closeEntry(); } }
关键注意点:
- 不要使用JDK原生
java.util.zip包下的压缩类,这类类在iOS等非Android移动平台存在兼容性问题,必须使用ZipSupport库提供的zip相关类- 写入目录条目时需要在路径末尾拼接
/,否则解压时会丢失目录结构,空目录也无法被正确识别- 所有流操作建议使用try-with-resources写法自动关闭,避免资源泄漏
- 若需要压缩沙盒外的公共存储文件,需要提前申请对应平台的文件读写权限
内容的提问来源于stack exchange,提问作者Daniel Tsai
相关产品推荐
相关产品推荐

