JAVA从入门到精通书中ZIP压缩和解压缩错误修正

本人买了一本Java从入门到精通书籍,学到zip压缩和解压这部分,发现按照书上的代码会出现问题,无法完成压缩和解压缩

首先是压缩原文代码:

public static void zip(String outputname,String filename) throws IOException{
File f=new File(filename);
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(outputname));
zip(out,f,“”);
out.close();
}

public static  void zip(ZipOutputStream out,File f,String base) throws IOException{
if(f.isDirectory()){
File[] files=f.listFiles();
//out.putNextEntry(new ZipEntry(base+"/"));
base=(base.length()==0)?"":base+"/";
for(int i=0;i<files.length;i++){
zip(out,files[i],base+files[i].getName());
}
}else{
out.putNextEntry(new ZipEntry(base));
FileInputStream in=new FileInputStream(f);
//BufferedInputStream bi=new BufferedInputStream(in);
int b;
System.out.println(base);
while(( b=in.read())!=-1){

out.write(b);
}
//bi.close();
in.close();
}
}

画删除线的代码是出错部分,在找入口点的时候,应该把当前的文件即getName()传过去

这是能实现该玩的代码

public static void zip(String outputname,String filename) throws IOException{
File f=new File(filename);
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(outputname));
zip(out,f,f.getName());
out.close();
}


解压缩,书中根本就没实现。。按书中的代码能解压,但解压出来文件全成了文件夹

修正代码:

public static void  dezip(String inputName,String deZipPath){
ZipInputStream zin;
try{
zin=new ZipInputStream(new FileInputStream(inputName));
ZipEntry entry;
while((entry=zin.getNextEntry())!=null){
if(entry.isDirectory()) continue;
File f=new File(deZipPath+entry.getName());
System.out.println(f.getAbsolutePath());
if(!f.exists()){
System.out.println(f.getParentFile());
//要是该文件的上级文件夹进行创建
(new File(f.getParent())).mkdirs();  
f.createNewFile();
}
int b;
if(f.isFile()){
FileOutputStream out=new FileOutputStream(f);
while((b=zin.read())!=-1){
out.write(b);
}
out.close();
}

zin.closeEntry();
}
zin.close();
}catch(Exception e){
e.printStackTrace();
}

}


菜鸟一只,第一篇博客!

你可能感兴趣的:(java,压缩,ZipOutputStream,ZipInputStream,从入门到精通)