先上代码
public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName) {
boolean flag = false;
File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
BufferedOutputStream bos=null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
if(sourceFile.exists() == false) {
System.out.println(">>>>>> 待压缩的文件目录:" + sourceFilePath + " 不存在. <<<<<<");
} else {
try {
File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
if(zipFile.exists()){
if(DeleteFile.delete(zipFilePath + "/" + fileName + ".zip")){
System.out.println(">>>>>> 删除" + 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 + " 里面不存在文件,无需压缩. <<<<<<");
} else {
fos = new FileOutputStream(zipFile);
bos =new BufferedOutputStream(fos);
zos = new ZipOutputStream(bos);
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);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis,1024*10);
int read = 0;
while((read=bis.read(bufs, 0, 1024*10)) != -1) {
zos.write(bufs, 0, read);
}
}
flag = true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
// 关闭流
try {
if(null != zos) zos.close();
if(null != bis) bis.close();
if(null != fis) fis.close();
if(null != bos) bos.close();
if(null != fos) fos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
return flag;
}
主要原因还是自己对流不熟悉,for多个文件时,直接给流new一个新对象,所有导致之前的流对象在java虚拟机中没有被回收,所有才有了
真的该好好复习基础知识了
解决:
在for循环里把流关掉
for(int i=0;i<sourceFiles.length;i++) {
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
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();
fis.close();
}
一直以为是java.util.zip.ZipEntry,java.util.zip.ZipOutputStream 没正确使用的问题