Created
March 29, 2017 09:44
-
-
Save zhmz1326/d2787af7801b0efaeb522a2c3979c599 to your computer and use it in GitHub Desktop.
Compress a directory to a zip stream using commons-compress and java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void compressZipfile(String sourceDir, OutputStream os) throws IOException { | |
ZipOutputStream zos = new ZipOutputStream(os); | |
compressDirectoryToZipfile(sourceDir, sourceDir, zos); | |
IOUtils.closeQuietly(zos); | |
} | |
private static void compressDirectoryToZipfile(String rootDir, String sourceDir, ZipOutputStream out) throws IOException, FileNotFoundException { | |
File[] fileList = new File(sourceDir).listFiles(); | |
if (fileList.length == 0) { // empty directory / empty folder | |
ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir, "") + "/"); | |
out.putNextEntry(entry); | |
out.closeEntry(); | |
} else { | |
for (File file : fileList) { | |
if (file.isDirectory()) { | |
compressDirectoryToZipfile(rootDir, sourceDir + File.separator + file.getName(), out); | |
} else { | |
ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir, "") + File.separator + file.getName()); | |
out.putNextEntry(entry); | |
FileInputStream in = new FileInputStream(sourceDir + File.separator + file.getName()); | |
IOUtils.copy(in, out); | |
IOUtils.closeQuietly(in); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment