//我写的方法如下,但是调用之后之前压缩的文件不在了,压缩文件里只是保留最后一个要压缩的文件,求大神解答
public boolean fileToZip(StringBuffer filePath, String zipFilePath, String fileName) {
System.out.println(">>>>>>开始压缩文件>>>文件路径" + filePath.toString() + ">>>压缩路径>>>" + zipFilePath + ">>>压缩文件名称:" + fileName + "<<<<<<");
boolean flag = false;
File sourceFile = new File(filePath.toString());// 创建文件
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
if (sourceFile.exists() == false) {
System.out.println(">>>>>> 待压缩的文件不存在:" + filePath.toString() + " 不存在. <<<<<<");
} else {
try {
File zipFile = new File(zipFilePath + "/" + fileName + ".zip");// 创建压缩文件
if (!zipFile.exists()) {
System.out.println("压缩文件不存在,创建压缩文件!!!");
zipFile.getParentFile().mkdirs();
zipFile.createNewFile();
}
fos = new FileOutputStream(zipFile,true);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024 * 10];
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFile.getName());
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFile);
bis = new BufferedInputStream(fis, 1024 * 10);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs, 0, read);
}
if (null != fis)
fis.close();
// sourceFiles[i].delete();
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
// 关闭流
try {
if (null != bis)
bis.close();
if (null != zos)
zos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
return flag;
}