jdk提供了zip相关的类方便的实现压缩和解压缩。使用方法很简单。下边分别是压缩和解压缩的简单事例
1,压缩的
import java.io.bufferedinputstream;
import java.io.bufferedoutputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.util.zip.zipentry;
import java.util.zip.zipoutputstream;


public class zip
{
static final int buffer = 2048;


public static void main(string argv[])
{

try
{
bufferedinputstream origin = null;
fileoutputstream dest = new fileoutputstream("e:\\test\\myfiles.zip");
zipoutputstream out = new zipoutputstream(new bufferedoutputstream(
dest));
byte data[] = new byte[buffer];
file f = new file("e:\\test\\a\\");
file files[] = f.listfiles();


for (int i = 0; i < files.length; i)
{
fileinputstream fi = new fileinputstream(files[i]);
origin = new bufferedinputstream(fi, buffer);
zipentry entry = new zipentry(files[i].getname());
out.putnextentry(entry);
int count;

while ((count = origin.read(data, 0, buffer)) != -1)
{
out.write(data, 0, count);
}
origin.close();
}
out.close();

} catch (exception e)
{
e.printstacktrace();
}
}
}

2,解压缩的。
import java.io.bufferedinputstream;
import java.io.bufferedoutputstream;
import java.io.file;
import java.io.fileoutputstream;
import java.util.enumeration;
import java.util.zip.zipentry;
import java.util.zip.zipfile;


public class unzip
{
static final int buffer = 2048;


public static void main(string argv[])
{

try
{
string filename = "e:\\test\\myfiles.zip";
string filepath = "e:\\test\\";
zipfile zipfile = new zipfile(filename);
enumeration emu = zipfile.entries();
int i=0;

while(emu.hasmoreelements())
{
zipentry entry = (zipentry)emu.nextelement();
//会把目录作为一个file读出一次,所以只建立目录就可以,之下的文件还会被迭代到。
if (entry.isdirectory())

{
new file(filepath entry.getname()).mkdirs();
continue;
}
bufferedinputstream bis = new bufferedinputstream(zipfile.getinputstream(entry));
file file = new file(filepath entry.getname());
//加入这个的原因是zipfile读取文件是随机读取的,这就造成可能先读取一个文件
//而这个文件所在的目录还没有出现过,所以要建出目录来。
file parent = file.getparentfile();

if(parent != null && (!parent.exists()))
{
parent.mkdirs();
}
fileoutputstream fos = new fileoutputstream(file);
bufferedoutputstream bos = new bufferedoutputstream(fos,buffer);
int count;
byte data[] = new byte[buffer];
while ((count = bis.read(data, 0, buffer)) != -1)

{
bos.write(data, 0, count);
}
bos.flush();
bos.close();
bis.close();
}
zipfile.close();

} catch (exception e)
{
e.printstacktrace();
}
}
}
