最近项目中使用Java实现zip/unzip XML文件的功能,Java自带的API可以方便实现文件的压缩和解压缩,记录一下相关代码。
public void zip(File src, File dest){
InputStream in = null;
ZipOutputStream zos= null;
try {
zos = new ZipOutputStream(new FileOutputStream(dest));
ZipEntry ze= new ZipEntry(src.getName());
zos.putNextEntry(ze);
in = new FileInputStream(src);
IOUtils.copy(in,zos);
} catch (IOException e) {
LOG.error("fail to zip file: " + src.getName() + " to : " + dest.getName());
throw e;
} finally {
if(null != zos){
try {
zos.closeEntry();
} catch (IOException ex){
}
}
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(zos);
}
public void unZip(File file, String outputFolder){
File folder = new File(outputFolder);
if(folder.exists() && folder.isFile()){
throw IllegalArgumentException("Not an exists folder");
}
//create output directory is not exists
if(!folder.exists() && !folder.mkdir()){
throw IllegalStatusException("fail to create dest folder");
}
InputStream in = null; OutputStream out = null;
ZipFile zipFile = new ZipFile(file);
Enumeration emu = zipFile.entries();
while(emu.hasMoreElements()){
ZipEntry entry = (ZipEntry)emu.nextElement();
//建立目录
if (entry.isDirectory()){
new File(outputFolder + entry.getName()).mkdirs();
continue;
}
//文件拷贝
InputStream is = zipFile.getInputStream(entry);
File file = new File(outputFolder + entry.getName());
//注意:zipfile读取文件是随机读取的,可能先读取一个文件,再读取文件夹,所以可能要先创建目录
File parent = file.getParentFile();
if(parent != null && (!parent.exists())){
parent.mkdirs();
}
out = new FileOutputStream(file);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}catch(IOException ex){
LOG.error(ex.getMessage());
throw ex;
} finally {
if(null != zipFile){
try{
zipFile.close();
} catch (IOException e) {
}
}
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
这代码最主要就是文件太大的话,IOUtils的copy耗CPU比较高。