文件压缩及解压
public abstract class ZipFileUtil {
protected final Logger logger = LoggerFactory.getLogger(ZipFileUtil.class);
public static void main(String args[]){
zip(new File("z:/config/config2"),false,new File("z:/config/config2.swf_back"));
}
/**
* 文件压缩
* @param folder 文件夹
* @param hasPath 是否包含文件目录结构
* @param zipFile 压缩后的ZIP文件
* @return
*/
public static boolean zip(File folder,boolean hasPath,File zipFile){
boolean ret = false;
ZipOutputStream out = null;
try{
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(zipFile);
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[1024];
File files[] = folder.listFiles();
for(int i = 0; i < files.length; i++){
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi,1024);
ZipEntry entry = new ZipEntry(files[i].getName());
out.putNextEntry(entry);
int count=-1;
while ((count = origin.read(data,0,1024)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
ret = true;
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(out!=null)out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
@SuppressWarnings("unchecked")
public static boolean unzip(File zipFile,boolean hasPath,File targetFolder){
boolean ret = false;
ZipFile _zipFile = null;
try{
String filePath = targetFolder.getAbsolutePath()+"/";
_zipFile = new ZipFile(zipFile);
Enumeration emu = _zipFile.entries();
while(emu.hasMoreElements()){
ZipEntry entry = (ZipEntry)emu.nextElement();
//会把目录作为一个file读出一次,所以只建立目录就可以,之下的文件还会被迭代到。
if (entry.isDirectory()) {
new File(filePath + entry.getName()).mkdirs();
continue;
}
System.out.println("-->"+filePath + entry.getName());
BufferedInputStream bis = new BufferedInputStream(_zipFile.getInputStream(entry));
File file = new File(filePath + entry.getName());
//加入这个的原因是zipfile读取文件是随机读取的,这就造成可能先读取一个文件
//而这个文件所在的目录还没有出现过,所以要建出目录来。
File parent = file.getParentFile();
if(parent != null && (!parent.exists())){
parent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos,1024);
int count;
byte data[] = new byte[1024];
while ((count = bis.read(data, 0,1024)) != -1){
bos.write(data, 0, count);
}
bos.flush();
bos.close();
bis.close();
}
ret = true;
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(_zipFile!=null)_zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
}