您的位置:首页 > 编程语言 > Java开发

java压缩文件方法

2014-02-12 13:26 99 查看
/**
* 压缩文件
* @param srcfile File[] 需要压缩的文件列表
* @param zipfile File    压缩后的文件
*/
public static void ZipFiles(java.io.File[] srcfile, java.io.File zipfile) {
byte[] buf = new byte[1024];
try {
// Create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
//ZipOutputStream out = new ZipOutputStream(Response.getOutputStream());--设置成这样可以不用保存在本地,再输出, 通过response流输出。
// Compress the files
for (int i = 0; i < srcfile.length; i++) {
FileInputStream in = new FileInputStream(srcfile[i]);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(srcfile[i].getName()));
// 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();
System.out.println("压缩完成.");
}catch (IOException e) {
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: