Following Code Snippet compresses a directory including its files (and subdirectories, if any) to a target zip file. The class name is DirectoryZipper and it takes the absolute path of the directory to be zipped and the target zipped file as input. The class is tested with the main method inside the class body itself.
This class utilizes java.util.zip and the code is commented for easy understanding.
The flow of the code is like
- Traverse the input directory recursively and generate a list of files to be zipped as per its path of it relative to the input directory path. These relative paths will be used in zip entry.
- Create file output stream out of target file path
- Create a zip output stream out of the file output stream
- Create the zip entries out of the entries in the list
- Put each entry to the zip output stream
- Create the file input stream out of the input file to be zipped as per the zip entry
- Finally, read the input file and write it to the zip output stream
Here goes the code
package com.t4b.util.zip.test;
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 TestMain {
private List files;
private String dirPath;
private String zipFilePath;
TestMain(String dirPath, String zipFilePath) {
this.dirPath = dirPath;
this.zipFilePath = zipFilePath;
files = new ArrayList();
generateListOfFiles(new File(dirPath));
}
private void generateListOfFiles(File node) {
if (node.isFile()) {
String absPathOfFile = node.getAbsoluteFile().toString();
String entry = generatePathRelativeToInputDirectory(absPathOfFile);
files.add(entry);
}
if (node.isDirectory()) {
String[] subNode = node.list();
for (String filename : subNode) {
generateListOfFiles(new File(node, filename));
}
}
}
private String generatePathRelativeToInputDirectory(String absPath) {
return absPath.substring(dirPath.length() + 1, absPath.length());
}
public void zip() {
byte[] buffer = new byte[1024];
try {
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String file : this.files) {
ZipEntry ze = new ZipEntry(file);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(dirPath + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
zos.close();
System.out.println("Zipped file is ready at " + zipFilePath);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
TestMain dirZipper = new TestMain("MyDir", "MyDir.zip");
dirZipper.zip();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.