AKHILESH MISHRA IN OCEAN OF JAVA

Ocean Of Java: Zip any file

Tuesday, May 22, 2007

Zip any file

The java program to zip any number of files.


import java.util.zip.*;
import java.io.*;

public class JavaZip
{

public static void main(String[] ak)
{

// These are the files to include in the ZIP file
String[] filenames = new String[]{ak[0]};

// Create a buffer for reading the files
byte[] buf = new byte[1024];

try {
// Create the ZIP file
String outFilename = "c:/Akhilesh/java/project/"+ak[0]+".zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));

// Compress the files
for (int i=0; i FileInputStream in = new FileInputStream(filenames[i]);

// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filenames[i]));

// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}

// Complete the entry
out.closeEntry();
in.close();
}

// Complete the ZIP file
out.close();
} catch (IOException e) {
}
}
}
Copy and paste the program, compile program passing the files location, and run.

No comments: