- Code: Select all
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CreateZipFile {
public static int BUFFER_SIZE = 10240;
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java makeZipFile " +
" [files to be zipped] [filename after zip] ");
return;
}
try {
String filename = args[0];
String zipfilename = args[1];
CreateZipFile list = new CreateZipFile();
//makeZipFile list = new makeZipFile( );
list.createZipArchive(new File(filename), new File(zipfilename));
} catch (Exception e) {
e.printStackTrace();
}
}
protected void createZipArchive(File archiveFile, File tobeZippedFiles) {
try {
byte buffer[] = new byte[BUFFER_SIZE];
// Open archive file
FileOutputStream stream = new FileOutputStream(archiveFile);
ZipOutputStream out = new ZipOutputStream(stream);
System.out.println("Adding " + tobeZippedFiles.getName());
// Add archive entry
ZipEntry zipAdd = new ZipEntry(tobeZippedFiles.getName());
zipAdd.setTime(tobeZippedFiles.lastModified());
out.putNextEntry(zipAdd);
// Read input & write to output
FileInputStream in = new FileInputStream(tobeZippedFiles);
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
in.close();
out.close();
stream.close();
System.out.println("Adding completed OK");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error: " + e.getMessage());
}
}
}
usage:
- Code: Select all
/opt/java1.3/bin/java -cp . CreateZipFile abc.zip testfile
