可以使用jdk提供的java.util.zip包的类来进行文件的压缩。下面的代码是对文件进行压缩的例子:
// 这是要进行压缩的文件
String[] source = new String[]{"source1", "source2"};
// 创建一个读取这些文件的缓冲区
byte[] buf = new byte[1024];
try {
//创建zip文件
String target = "target.zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));
// 对上面的几个文件进行压缩
for (int i=0; i<source.length; i++) {
FileInputStream in = new FileInputStream(source[i]);
// 添加zip到输出流
out.putNextEntry(new ZipEntry(source[i]));
// 把需要压缩文件的字节流传输到ZIP文件
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// 完成创建
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
} catch (IOException e) {
}