Write a class that creates and reads a ZIP file with java.util.zip
Share with you
There's a recursive call inside.
Oh
Recently used a lot of recursive calls! Have a short summary!
/**
Testzip.java
coding by Serol Luo.
rollingpig@163.com
2003/07/03
http://www.chinaunix.net/forum/viewforum.php?f=26
Reprint Please keep this information
*/
import java.util.*;
import java.util.zip.*;
import java.io.*;
class Testzip
{
public void Zip (String zipfilename,string inputfile) throws exception{
Zip (zipfilename,new File (inputfile));
}
public void Zip (String zipfilename,file inputfile) throws exception{
zipoutputstream out=new Zipoutputstream (New FileOutputStream (Zipfilename));
Zip (Out,inputfile, "");
System.out.println ("Zip done");
Out.close ();
}
public void Unzip (String zipfilename,string outputdirectory) throws exception{
zipinputstream in=new Zipinputstream (New FileInputStream (Zipfilename));
ZipEntry Z;
while ((Z=in.getnextentry ())!= null)
{
System.out.println ("unziping" +z.getname ());
if (z.isdirectory ())
{
String name=z.getname ();
name=name.substring (0,name.length ()-1);
file F=new file (outputdirectory+file.separator+name);
F.mkdir ();
System.out.println ("mkdir" +outputdirectory+file.separator+name);
}
else{
file F=new file (Outputdirectory+file.separator+z.getname ());
F.createnewfile ();
FileOutputStream out=new FileOutputStream (f);
int b;
while ((B=in.read ())!=-1)
Out.write (b);
Out.close ();
}
}
In.close ();
}
public void Zip (Zipoutputstream out,file f,string base) throws exception{
System.out.println ("Zipping" +f.getname ());
if (f.isdirectory ())
{
file[] Fl=f.listfiles ();
Out.putnextentry (New ZipEntry (base+ "/"));
base=base.length () ==0? ": base+"/";
for (int i=0;i<fl.length; i++)
{
Zip (Out,fl[i],base+fl[i].getname ());
}
}
Else
{
Out.putnextentry (new ZipEntry (base));
FileInputStream in=new FileInputStream (f);
int b;
while ((B=in.read ())!=-1)
Out.write (b);
In.close ();
}
}
public static void Main (string[] args)
{
try{
testzip t=new testzip ();
t.zip ("C:\\test.zip", "c:\\test");
t.unzip ("C:\\test.zip", "C:\\test2");
}
catch (Exception e) {e.printstacktrace (System.out);}
}
}