說(shuō)明:
1.平時(shí)做zip打包主要用到了java.util.zip下的ZipOutputStream、ZipEntry兩個(gè)API
如需了解這兩個(gè)API怎么用钝鸽,請(qǐng)自行查閱文檔汇恤。
2.以下方法已經(jīng)經(jīng)過(guò)測(cè)試,可直接copy使用寞埠,如有不足之處請(qǐng)指出。謝謝焊夸!
/**
* 壓縮文件列表到某個(gè)zip包
* @param zipFileName zip包文件名
* @param paths 文件列表路徑
* @throws IOException
*/
public static void compress(String zipFileName,String... paths) throws IOException {
compress(new FileOutputStream(zipFileName),paths);
}
/**
* 壓縮文件列表到某個(gè)zip包
* @param stream 流
* @param paths 文件列表路徑
* @throws IOException
*/
public static void compress(OutputStream stream,String... paths) throws IOException {
ZipOutputStream zos = new ZipOutputStream(stream);
for (String path : paths){
if (StringUtils.equals(path,"")){
continue;
}
File file = new File(path);
if (file.exists()){
if (file.isDirectory()){
zipDirectory(zos,file.getPath(),file.getName() + File.separator);
} else {
zipFile(zos,file.getPath(),"");
}
}
}
zos.close();
}
/**
* 解析多文件夾
* @param zos zip流
* @param dirName 目錄名稱
* @param basePath
* @throws IOException
*/
private static void zipDirectory(ZipOutputStream zos,String dirName,String basePath) throws IOException {
File dir = new File(dirName);
if (dir.exists()){
File files[] = dir.listFiles();
if (files.length > 0){
for (File file : files){
if (file.isDirectory()){
zipDirectory(zos,file.getPath(),file.getName() + File.separator);
} else {
zipFile(zos,file.getName(),basePath);
}
}
} else {
ZipEntry zipEntry = new ZipEntry(basePath);
zos.putNextEntry(zipEntry);
}
}
}
private static void zipFile(ZipOutputStream zos,String fileName,String basePath) throws IOException {
File file = new File(fileName);
if (file.exists()){
FileInputStream fis = new FileInputStream(fileName);
ZipEntry ze = new ZipEntry(basePath + file.getName());
zos.putNextEntry(ze);
byte[] buffer = new byte[8192];
int count = 0;
while ((count = fis.read(buffer)) > 0){
zos.write(buffer,0,count);
}
fis.close();
}
}