码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-09-22 23:01:23      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   java   ar   for   文件   

最近进行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; 
}

}
}

 

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

标签:style   blog   color   io   os   java   ar   for   文件   

原文地址:http://www.cnblogs.com/allforone/p/3986682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!