下面介绍的是使用Apache的Ant.jar 包来实现对文件的压缩和解压
首先是压缩文件的代码
fList 中的内容是文件的路径
ZipEntry 中用到的index是为了方便从文件路劲中截取文件名
//压缩文件使用使用Apache的ANT包下的方法
public void fileToZip(List<String> fList,String targerFile,int index)
{
//创建Zip输出流对象
try {
FileOutputStream fos=new FileOutputStream(targerFile);
ZipOutputStream zipOut=new ZipOutputStream(fos);
byte buffer[]=new byte[1024];
for(String path:fList)
{
//创建输入流对象
FileInputStream fis=new FileInputStream(path);
ZipEntry en=new ZipEntry(path.substring(index));
zipOut.putNextEntry(en);
int len=0;
while((fis.read(buffer))!=-1)
{
zipOut.write(buffer, 0, len);
}
zipOut.closeEntry();
fis.close();
}
zipOut.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
下面是对文件解压的代码
list主要用来记录一下都解压出了什么文件
//解压文件 使用Apache下的ANT包
@SuppressWarnings("unchecked")
public void ZIPtoFile(String sourceFile,String targerPath,List<String> list)
{
// ZipFile zipFile=new ZipFile(sourceFile);
// Enumeration<ZipEntry> e=zipFile.get
ZipFile zf=null;
try {
zf = new ZipFile(sourceFile);
Enumeration<ZipEntry> e = zf.getEntries();// 获得所有ZipEntry对象
while(e.hasMoreElements())
{
ZipEntry zn=e.nextElement();
if(!zn.isDirectory())
{
File newFile=new File(targerPath+File.separator+zn.getName());
list.add(newFile.getAbsolutePath());
new File(newFile.getParent()).mkdirs();//这里要注意,创建这个父路径;
//newFile.mkdirs();
newFile.createNewFile();
FileOutputStream output=new FileOutputStream(newFile);
InputStream in=zf.getInputStream(zn);
int read=0;
while((read=in.read())!=-1)
{
output.write(read);
}
output.close();
}
}
} catch (ZipException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
使用Apache的Ant的好处是可以避免中文乱码的问题