我是
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);
- }
- }
- }