最近碰到个需要打包文件成压缩包的项目,需要注意压缩输出流ZipOutputStream应该在finally中关闭,提前关闭或者不关闭都会导致压缩失败。
下面直接上代码:
//递归压缩文件工具类
public class ZipUitls {
/**
*
* @param zos 生成的压缩文件
* @param sources File 需要压缩的文件,可以是文件夹
* @param name 保存到压缩文件的文件名称
* @throws IOException
*/ public void fileToZip( Zip OutputStream zos,File sourcesFile,String name) throws IO Exception {
//遍历文件夹的文件
File[] files = sourcesFile.listFiles();
for (File file : files) {
//如果是文件,则压缩到zos压缩文件中
if (file.isFile()){
//文件输入流
FileInputStream inputStream = new FileInputStream(file);
zos.putNextEntry(new ZipEntry(name + File.separator + file.getName()));
byte [] bytes = new byte[2048];
int length;
while ((length = inputStream.read(bytes)) != -1){
zos.write(bytes);
}
}else {
//如果是文件夹,则递归
if (file.listFiles().length == 0){ //如果只是空文件夹,则只保留一个目录
zos.putNextEntry(new ZipEntry(name + File.separator + file.getName() + "/"));
}
//如果文件夹里面有内容,则递归
fileToZip(zos,file,name + File.separator + file.getName());
}
}
}
}
//测试类
public void testZip() throws IOException {
long start = System.currentTimeMillis();
System.out.println(start);
ZipUitls zipUitls = new ZipUitls();
ZipOutputStream zos = null;
FileOutputStream fos = null;
try {
//压缩输出的文件为:D:\ceshi.zip
fos = new FileOutputStream("D:" + File.separator + "ceshi.zip");
zos = new ZipOutputStream(fos);
//压缩源文件
File sourceFile = new File("D:" + File.separator + "hello");
//调用ZipUitls中的压缩方法
zipUitls.fileToZip(zos,sourceFile,sourceFile.getName());
}catch (FileNotFoundException e) {
throw new RuntimeException(e);
}finally {
//ZipOutputStream压缩输出流在finally处关闭,不然压缩失败
if (zos != null){
zos.close();
}
if (fos != null){
fos.close();
}
}
long end = System.currentTimeMillis();
System.out.println(end);
System.out.println(end - start);
}