java – 使用Commons IO将目录压缩到zipfile中
发布时间:2020-12-14 17:43:14 所属栏目:Java 来源:网络整理
导读:我是 Java编程的初学者,目前正在编写一个必须能够压缩和解压缩.zip文件的应用程序.我可以使用以下代码使用内置的Java zip功能以及Apache Commons IO库解压缩Java中的zipfile: public static void decompressZipfile(String file,String outputDir) throws I
我是
Java编程的初学者,目前正在编写一个必须能够压缩和解压缩.zip文件的应用程序.我可以使用以下代码使用内置的Java zip功能以及Apache Commons IO库解压缩Java中的zipfile:
public static void decompressZipfile(String file,String outputDir) throws IOException { if (!new File(outputDir).exists()) { new File(outputDir).mkdirs(); } ZipFile zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(outputDir,entry.getName()); if (entry.isDirectory()) { entryDestination.mkdirs(); } else { InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination); IOUtils.copy(in,out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } 除了我以前使用的外部库之外,我将如何从目录创建zip文件? (Java标准库和Commons IO) 解决方法
以下方法似乎成功地递归压缩目录:
public static void compressZipfile(String sourceDir,String outputFile) throws IOException,FileNotFoundException { ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile)); compressDirectoryToZipfile(sourceDir,sourceDir,zipFile); IOUtils.closeQuietly(zipFile); } private static void compressDirectoryToZipfile(String rootDir,String sourceDir,ZipOutputStream out) throws IOException,FileNotFoundException { for (File file : new File(sourceDir).listFiles()) { if (file.isDirectory()) { compressDirectoryToZipfile(rootDir,sourceDir + File.separator + file.getName(),out); } else { ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir,"") + file.getName()); out.putNextEntry(entry); FileInputStream in = new FileInputStream(sourceDir + file.getName()); IOUtils.copy(in,out); IOUtils.closeQuietly(in); } } } 正如我的压缩代码片段所示,我正在使用IOUtils.copy()来处理流数据传输. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |