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

java zip压缩优化版 解决压缩后文件一直被占用无法删除

2014-09-22 20:32 477 查看
最近进行zip操作,从网上找到一个处理方法,但是经过试验存在一些bug,主要是文件流的申明存在问题,导致jvm一直占用文件而不释放,特意把自己修改的发出来,已备记录

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zippic {

public final static class FileToZip {

private FileToZip() {

}

/**
* 将存放在sourceFilePath目录下的源文件,打包成fileName名称的ZIP文件,并存放到zipFilePath。
* @param sourceFilePath 待压缩的文件路径
* @param zipFilePath 压缩后存放路径
* @param fileName 压缩后文件的名称
* @return flag
*/
public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName) {
boolean flag = false;
File sourceFile = new File(sourceFilePath);
if(sourceFile.exists() == false) {
System.out.println(">>>>>> 待压缩的文件目录:" + sourceFilePath + " 不存在. <<<<<<");
flag = false;
return flag;
} else {
try {
File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
if(zipFile.exists()) {
System.out.println(">>>>>> " + zipFilePath + " 目录下存在名字为:" + fileName + ".zip" + " 打包文件. <<<<<<");
} else {
File[] sourceFiles = sourceFile.listFiles();
if(null == sourceFiles || sourceFiles.length < 1) {
System.out.println(">>>>>> 待压缩的文件目录:" + sourceFilePath + " 里面不存在文件,无需压缩. <<<<<<");
flag = false;
return flag;
} else {
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
                   //用到时才申明,否则容易出现问题,记得先开后关,后开先关
byte[] bufs = new byte[1024*10];               //缓冲块
for(int i=0;i<sourceFiles.length;i++) {
                  // 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
                // 读取待压缩的文件并写进压缩包里
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFiles[i]),1024*10);
                   //用到时才申明,否则容易出现问题,记得先开后关,后开先关
int read = 0;
while((read=(bis.read(bufs, 0, 1024*10))) != -1) {
zos.write(bufs, 0, read);
}
if(null != bis) bis.close();  //关闭
}
flag = true;
if(null != zos) zos.close();  //关闭
}

}

} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}

return flag;
}

}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: