java中文件压缩
package ziiptest.com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author Administrator
*
*/
public class ZipTest {
/**
* @param args
*/
private void zip1(File srcf,File desf) throws Exception{
ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(desf));
zip2(zos,srcf,"");
System.out.println("压缩中。。。");
zos.close();
}
private void zip2(ZipOutputStream zos,File srcf,String path)throws Exception{
if(srcf.isDirectory()){
File sonfile[]=srcf.listFiles();
zos.putNextEntry(new ZipEntry(path+"/"));
path=path.length()==0?"":path+"/";
for(int i=0;i<sonfile.length;i++){
zip2(zos,sonfile[i],sonfile[i].getParent());
}
}
else{
zos.putNextEntry(new ZipEntry(path));
FileInputStream in=new FileInputStream(srcf);
byte b[]=new byte[1024];
int k;
while(-1 != (k=in.read(b))){
zos.write(b,0,k);
};
in.close();
}
System.out.println("压缩成功!");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
File srcf=new File("F:\\myeclipsecase\\IoExample\\test");
File desf=new File("F:\\myeclipsecase\\IoExample\\test");
ZipTest zip=new ZipTest();
try {
zip.zip1(srcf, desf);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
当我把test分别改为test.txt和test.zip是可以,但是如果要压缩一个文件夹就会报错 ,错误在for第二次循环中,对ZipEntry(path)不是很了解,谁知道他是什么意思path指的是什么?
------解决方案--------------------什么错误?看你原源目录和目的目录是一样的,当然会错了。压缩完他,有放这个目录里,你认为可能吗?