在别的代码中摘取的代码自己整合了一下 还是有一些问题 有大神看见可以指点一下
/**
* 压缩文件(.zip)的函数
*
* @param zipDirectory:(需要)压缩的文件夹路径
* @param zipPath:文件压缩后放置的路径,该路径可以为null,null表示压缩到原文件的同级目录
* @return :返回一个压缩好的文件(File),否则返回null
*/
public static File doZip(String zipDirectory, String zipPath) {
File zipDir = new File(zipDirectory);
ZipOutputStream zipOut = null;
if (zipPath == null) {
zipPath = zipDir.getParent();
}
// 压缩后生成的zip文件名
String zipFileName = zipPath + "/" + zipDir.getName() + "new.zip";
File sf = new File(zipFileName);
if (!sf.isFile()) {
try {
sf.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
zipOut = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(zipFileName)));
// 压缩文件
handleDir(zipDir, zipDir.getParent().length() + 1, zipOut);
return new File(zipFileName);
} catch (IOException e) {
logger.error("压缩失败");
e.printStackTrace();
return null;
} finally {
try {
if (zipOut != null){
zipOut.closeEntry();
zipOut.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
/**
* 由doZip调用,递归完成目录文件读取
*
* @param dir:(需要)压缩的文件夹(File 类型)
* @param len:一个参数(记录压缩文件夹的parent路径的长度)
* @param zipOut:需要压缩进的压缩文件
* @throws IOException:如果出错,会抛出IOE异常
*/
private static void handleDir(File dir, int len, ZipOutputStream zipOut)
throws IOException {
FileInputStream fileIn = null;
File[] files = dir.listFiles();
byte[] buf = new byte[1024 * 10];
int readedBytes;
try {
if (files != null) {
// 如果目录不为空,则分别处理目录和文件.
if (files.length > 0) {
for (File fileName : files) {
if (fileName.isDirectory()) {
handleDir(fileName, len, zipOut);
} else {
fileIn = new FileInputStream(fileName);
zipOut.putNextEntry(new ZipEntry(fileName.getPath()
.substring(len).replaceAll("\\\\", "/")));
while ((readedBytes = fileIn.read(buf)) > 0) {
zipOut.write(buf, 0, readedBytes);
}
zipOut.closeEntry();
fileIn.close();
}
}
} else { // 如果目录为空,则单独创建之.
zipOut.putNextEntry(new ZipEntry(dir.getPath().substring(len) + "/"));
zipOut.closeEntry();
}
} else {// 如果是一个单独的文件
fileIn = new FileInputStream(dir);
zipOut.putNextEntry(new ZipEntry(dir.getPath().substring(len)));
while ((readedBytes = fileIn.read(buf)) > 0) {
zipOut.write(buf, 0, readedBytes);
}
zipOut.closeEntry();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (zipOut != null){
zipOut.closeEntry();
zipOut.close();
}
if (fileIn != null) {
fileIn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}