Monday, September 22, 2008

Creating zip/jar files programmatically in Java

Creating zip/jar files programmatically in Java

Write a Java application which automatically zips the directories. The application should accept the input and output directories specified either through command prompt or via a properties file. The user should be able to specify From Date and To Date if s/he wishes so that only those directories in the specified input directory which have their last modified date in that range get zipped.

public class CreateZip{

private static FileOutputStream fos = null;
private static ZipOutputStream zos = null;
private static int BUFFER = 2048;
private static String inputDir = "C:\\input";
private static String outputDir = "C:\\output";
private static Date fromDate = null;
private static Date toDate = null;
private static boolean ZIP_ALL = false;

public CreateZip(){

public static void checkDirectories(){

File inputDirectory = new File(getInputDir());
File[] dirList = null;

dirList = inputDirectory.listFiles();
int len = dirList.length;

for(int i = 0; i< dir =" dirList[i];" lastmodified =" dir.lastModified();"> fromDate.getTime()
|| lastModified == fromDate.getTime())
&& (lastModified < lastmodified ="=" filelist =" dir.listFiles();" nooffiles =" fileList.length;" nooffiles ="=" zipfilename =" getOutputDir()" fos =" new" zos =" new" i =" 0;" fis =" new" bis =" new" zipentry =" new" data =" new" bytecount =","> -1){
zos.write(data, 0, byteCount);
System.out.println(filePath + " added");
} catch(Exception e){
System.out.println("Exception thrown while reading the file: " + e);

public static void main(String[] args){
if(args.length == 0)
else if(args.length == 2){
else if(args.length == 4){

//... using deprecated method just for testing
setFromDate(new Date(args[2]);
setToDate(new Date(args[3]);
System.out.println("Incorrect Usage!");

System.out.println("Starting the zipping process...");
System.out.println("Completed the zipping process!");

//... getters and setters of the fields

This draft version of the application is just to give you an idea of how easily can you write a Java application to automate the zipping process.

Similarly, you can create JAR file automatically using an almost identical Java program. You just need to change 'ZipOutputStream' with 'JarOutputStream', 'ZipEntry' with 'JarEntry' and probably you're done! Just try out in case you find it interesting.

Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.


1 comment:

Rohit said...

I was looking for it for sometime. Thankfully u posted it. I could run the program and it worked. Thanks Geek.