You are on page 1of 2

ZipIt.

java

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

public class ZipIt {


public static void main(String args[]) throws IOException {

// kiem tra doi so vao


if (args.length < 2) {
System.err.println("Cach su dung: java ZipIt tenFileZip.zip file1 file2
file3");
System.exit(-1);
}
File zipFile = new File(args[0]);
if (zipFile.exists()) {
System.err.println("file nen da ton tai, hay nhap ten khac");
System.exit(-2);
}

// stream output cua file


FileOutputStream fos = new FileOutputStream(zipFile);

// stream output cua file nen


ZipOutputStream zos = new ZipOutputStream(fos);
int bytesRead;

// tao bo dem
byte[] buffer = new byte[1024];

// check loi
CRC32 crc = new CRC32();

// thuc hien nen tung file vao trong file nen


for (int i=1, n=args.length; i < n; i++) {
String name = args[i];
File file = new File(name);
if (!file.exists()) {
System.err.println("Bo qua file : " + name);
continue;
}
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
crc.reset();
while ((bytesRead = bis.read(buffer)) != -1) {
crc.update(buffer, 0, bytesRead);
}
bis.close();
// reset de dua du lieu vao buffer chuan bi zip
bis = new BufferedInputStream( new FileInputStream(file));

// tao entry cho file nen


ZipEntry entry = new ZipEntry(name);

// thiet lap phuong phap nen


entry.setMethod(ZipEntry.STORED);
// thiet lap do kich thuoc file nen
entry.setCompressedSize(file.length());

Page 1
ZipIt.java

// thiet lap kich thuoc


entry.setSize(file.length());
// thiet lap loi crc
entry.setCrc(crc.getValue());
zos.putNextEntry(entry);
// nen du lieu trong buffer cho toi khi het du lieu -> quay lai vong lap voi
file khac
while ((bytesRead = bis.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
bis.close();
}
zos.close();
}
}

Page 2

You might also like