如何使用java压缩文件夹本身

假设我有以下目录结构。

D:\reports\january\ 

一月份里面有两个excel文件说A.xls和B.xls。 有很多关于如何使用java.util.zip压缩文件的地方。 但是我想将报告文件夹内的january文件夹压缩到报告文件夹中,以便报告中将包含一月份和一月份.zip 。 ( 这意味着当我解压缩january.zip文件,我应该得到1月文件夹 )。

任何人都可以请提供我使用java.util.zip的代码。 请让我知道这是否可以通过使用其他库更容易完成。

非常感谢…

它可以通过包java.util.Zip轻松解决,不需要任何额外的Jar文件

只需复制下面的代码并使用IDE run it

  //Import all needed packages package general; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtils { private List <String> fileList; private static final String OUTPUT_ZIP_FILE = "Folder.zip"; private static final String SOURCE_FOLDER = "D:\\Reports"; // SourceFolder path public ZipUtils() { fileList = new ArrayList < String > (); } public static void main(String[] args) { ZipUtils appZip = new ZipUtils(); appZip.generateFileList(new File(SOURCE_FOLDER)); appZip.zipIt(OUTPUT_ZIP_FILE); } public void zipIt(String zipFile) { byte[] buffer = new byte[1024]; String source = new File(SOURCE_FOLDER).getName(); FileOutputStream fos = null; ZipOutputStream zos = null; try { fos = new FileOutputStream(zipFile); zos = new ZipOutputStream(fos); System.out.println("Output to Zip : " + zipFile); FileInputStream in = null; for (String file: this.fileList) { System.out.println("File Added : " + file); ZipEntry ze = new ZipEntry(source + File.separator + file); zos.putNextEntry(ze); try { in = new FileInputStream(SOURCE_FOLDER + File.separator + file); int len; while ((len = in .read(buffer)) > 0) { zos.write(buffer, 0, len); } } finally { in.close(); } } zos.closeEntry(); System.out.println("Folder successfully compressed"); } catch (IOException ex) { ex.printStackTrace(); } finally { try { zos.close(); } catch (IOException e) { e.printStackTrace(); } } } public void generateFileList(File node) { // add file only if (node.isFile()) { fileList.add(generateZipEntry(node.toString())); } if (node.isDirectory()) { String[] subNote = node.list(); for (String filename: subNote) { generateFileList(new File(node, filename)); } } } private String generateZipEntry(String file) { return file.substring(SOURCE_FOLDER.length() + 1, file.length()); } } 

参考mkyong ..我改变了当前问题的要求的代码

你尝试过Zeroturnaround Zip库吗? 这真的很整洁! 拉一个文件夹只是一个单行:

 ZipUtil.pack(new File("D:\\reports\\january\\"), new File("D:\\reports\\january.zip")); 

(感谢OlegŠelajev的例子)

这是一个非常简洁的Java 7+解决scheme,完全依赖于vanilla JDK类,不需要任何第三方库:

 public static void pack(final Path folder, final Path zipFilePath) throws IOException { try ( FileOutputStream fos = new FileOutputStream(zipFilePath.toFile()); ZipOutputStream zos = new ZipOutputStream(fos) ) { Files.walkFileTree(folder, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { zos.putNextEntry(new ZipEntry(folder.relativize(file).toString())); Files.copy(file, zos); zos.closeEntry(); return FileVisitResult.CONTINUE; } public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { zos.putNextEntry(new ZipEntry(folder.relativize(dir).toString() + "/")); zos.closeEntry(); return FileVisitResult.CONTINUE; } }); } } 

它复制文件folder所有文件,包括空目录,并在zipFilePath创build一个zip压缩文件。

这是Java 8+的例子:

 public static void pack(String sourceDirPath, String zipFilePath) throws IOException { Path p = Files.createFile(Paths.get(zipFilePath)); try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) { Path pp = Paths.get(sourceDirPath); Files.walk(pp) .filter(path -> !Files.isDirectory(path)) .forEach(path -> { ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString()); try { zs.putNextEntry(zipEntry); Files.copy(path, zs); zs.closeEntry(); } catch (IOException e) { System.err.println(e); } }); } } 

Java 7+,commons.io

 public final class ZipUtils { public static void zipFolder(final File folder, final File zipFile) throws IOException { zipFolder(folder, new FileOutputStream(zipFile)); } public static void zipFolder(final File folder, final OutputStream outputStream) throws IOException { try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) { processFolder(folder, zipOutputStream, folder.getPath().length() + 1); } } private static void processFolder(final File folder, final ZipOutputStream zipOutputStream, final int prefixLength) throws IOException { for (final File file : folder.listFiles()) { if (file.isFile()) { final ZipEntry zipEntry = new ZipEntry(file.getPath().substring(prefixLength)); zipOutputStream.putNextEntry(zipEntry); try (FileInputStream inputStream = new FileInputStream(file)) { IOUtils.copy(inputStream, zipOutputStream); } zipOutputStream.closeEntry(); } else if (file.isDirectory()) { processFolder(file, zipOutputStream, prefixLength); } } } } 

我通常使用一个我曾经为此任务写过的助手类:

 import java.util.zip.*; import java.io.*; public class ZipExample { public static void main(String[] args){ ZipHelper zippy = new ZipHelper(); try { zippy.zipDir("folderName","test.zip"); } catch(IOException e2) { System.err.println(e2); } } } class ZipHelper { public void zipDir(String dirName, String nameZipFile) throws IOException { ZipOutputStream zip = null; FileOutputStream fW = null; fW = new FileOutputStream(nameZipFile); zip = new ZipOutputStream(fW); addFolderToZip("", dirName, zip); zip.close(); fW.close(); } private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException { File folder = new File(srcFolder); if (folder.list().length == 0) { addFileToZip(path , srcFolder, zip, true); } else { for (String fileName : folder.list()) { if (path.equals("")) { addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false); } else { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false); } } } } private void addFileToZip(String path, String srcFile, ZipOutputStream zip, boolean flag) throws IOException { File folder = new File(srcFile); if (flag) { zip.putNextEntry(new ZipEntry(path + "/" +folder.getName() + "/")); } else { if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip); } else { byte[] buf = new byte[1024]; int len; FileInputStream in = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } } } } } 

我将使用Apache Ant ,它具有一个API来从Java代码而不是从XML构build文件中调用任务。

 Project p = new Project(); p.init(); Zip zip = new Zip(); zip.setProject(p); zip.setDestFile(zipFile); // a java.io.File for the zip you want to create zip.setBasedir(new File("D:\\reports")); zip.setIncludes("january/**"); zip.perform(); 

在这里,我告诉它从基本目录D:\reports并压缩january文件夹和其中的一切。 生成的zip文件中的path将与相对于D:\reports的原始path相同,因此它们将包含january前缀。

您将不得不添加文件夹中的每个文件,并recursion遍历子文件夹。 如果你谷歌它有很多例子。

尝试这个:

  import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Zip { public static void main(String[] a) throws Exception { zipFolder("D:\\reports\\january", "D:\\reports\\january.zip"); } static public void zipFolder(String srcFolder, String destZipFile) throws Exception { ZipOutputStream zip = null; FileOutputStream fileWriter = null; fileWriter = new FileOutputStream(destZipFile); zip = new ZipOutputStream(fileWriter); addFolderToZip("", srcFolder, zip); zip.flush(); zip.close(); } static private void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws Exception { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip); } else { byte[] buf = new byte[1024]; int len; FileInputStream in = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } } } static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws Exception { File folder = new File(srcFolder); for (String fileName : folder.list()) { if (path.equals("")) { addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip); } else { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip); } } } } 

Java 6 +

 import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Zip { private static final FileFilter FOLDER_FILTER = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }; private static final FileFilter FILE_FILTER = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile(); } }; private static void compress(File file, ZipOutputStream outputStream, String path) throws IOException { if (file.isDirectory()) { File[] subFiles = file.listFiles(FILE_FILTER); if (subFiles != null) { for (File subFile : subFiles) { compress(subFile, outputStream, new File(path, subFile.getName()).getAbsolutePath()); } } File[] subDirs = file.listFiles(FOLDER_FILTER); if (subDirs != null) { for (File subDir : subDirs) { compress(subDir, outputStream, new File(path, subDir.getName()).getAbsolutePath()); } } } else if (file.exists()) { outputStream.putNextEntry(new ZipEntry(path)); FileInputStream inputStream = new FileInputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) >= 0) { outputStream.write(buffer, 0, len); } outputStream.closeEntry(); } } public static void compress(String dirPath, String zipFilePath) throws IOException { File file = new File(dirPath); final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFilePath)); compress(file, outputStream, "/"); outputStream.close(); } }