关于压缩文件后删除源文件的一点问题 |
您所在的位置:网站首页 › 解压后源文件能删除吗 › 关于压缩文件后删除源文件的一点问题 |
近期在项目中,需要压缩文件,同时压缩文件后需要删除源文件,
public static boolean fileToZip(String sourceFilePath,String zipFilePath,String zipFileName){
boolean flag = false;
File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
if (!sourceFile.exists()){
log.error("待压缩的文件目录,sourceFilePath={},不存在",sourceFilePath );
}else {
try {
File zipFile = new File(zipFilePath + File.separator + zipFileName + ".zip");
if (zipFile.exists()){
log.error("文件已存在,zipFile={}",zipFile );
} else {
File[] files = sourceFile.listFiles();
if (files != null && files.length > 0){
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024*10];
for (File file : files) {
//创建zip实体并添加进压缩包
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
//读取待压缩的文件, 并写进压缩包
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis,1024*10);
int read = 0;
while ((read = bis.read(bufs,0 ,1024*10 )) != -1){
zos.write(bufs,0 ,read );
}
//这句一开始没有,
bis.close();
}
flag = true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭流
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
File[] files = sourceFile.listFiles();
for (File file : files) {
//删除源文件
file.delete();
}
}
}
return flag;
}
刚开始一直删不掉,也判断是流没有关闭,后来在大佬提示下, fis = new FileInputStream(file); bis = new BufferedInputStream(fis,1024*10);才明白,我的这两个流,因为是在循环体里面放的,会造成堆栈的孤岛问题, 我每次循环一次就新建了一个input流,导致之前的input流成为栈内存中的孤岛,没有被GC回收,占用了文件,才会一直删不掉,后来在 循环体中 加上 bis.close();bingo,问题解决 思考: 对于基础的堆栈的不熟悉,导致了这个问题卡了我一下午,有空还是应该多看看java的基础,不能觉得基础不重要!!!! |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |