1.压缩方法
/**
* 压缩成ZIP 方法2
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.调用方法
public static void main(String[] args){
List<File> versionZip=new ArrayList<>();
//需要压缩文件地址
versionZip.add(new File("d:test/file.db"));
versionZip.add(new File("d:test/file.int"));
//压缩文件地址以及文件名
String fileZip="d:/tse/file.zip";
OutputStream os=null;
try {
os=new FileOutputStream(new File(fileZip));
//调用压缩方法
toZip(versionZip,os);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
//关闭流
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}