压缩文件
ZipOutputStream(OutpuStream out)
方法 | 返回值 | 说明 |
---|---|---|
putNextEntry(ZipEntry e) | void | 开始写一个新地ZipEntry,并将流内的位置移至此entry所指的数据开头 |
write(byte[] b, int off, int len) | void | 将字节数组写入当前ZIP条目数据 |
finish() | void | 完成写入ZIP输出流的内容,无需关闭它所配合的OutputStream |
setComment(String comment) | void | 可设置此ZIP的注释文字 |
public class MyZip
{
private void zip(String zipFileName, File inputFile) throws Exception
{
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip(out, inputFile, "");
System.out.println("压缩中。。。");
out.close();
}
private void zip(ZipOutStream out, File f, String base) throws Exception
{
if(f.isDirectory())
{
File[] f1 = f.listFiles();
if(base.length()!=0)
{
out.putNextEntry(new ZipEntry(base + "/"));
}
for(int i=0;i<f1.length;i++)
{
zip(out, f1[i], base + fl[i]);
}
}else{
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
System.out.println(base);
while((b=in.read())!=-1){
out.write(b);
}
in.close();
}
}
public static void main(String[] args)
{
MyZip book = new MyZip();
try{
book.zip("E:/hello.zip", new File("E:/hello"));
System.out.println("压缩完成!");
}catch(Exception e){
}
}
}
解压文件
ZipOutputStream(InputStream input)
方法 | 返回值 | 说明 |
---|---|---|
read(byte[] b, int off, int len) | int | 读取目标b 数组内off 偏移量的位置,长度是len 字节 |
available() | int | 判断是否已读完目前entry 所指定的数据。完成返回0 ,否则返回1 |
colseEntry() | void | 关闭当前ZIP条目并定位流以读取下一条目 |
skip(long n) | long | 跳过当前ZIP条目中指定的字节数 |
getNextEntry() | ZipEntry | 读取下一个ZipEntry ,并将流内的位置移至该entry 所指数据开头 |
creatZipEntry(String name) | ZipEntry | 以指定的name 参数新建一个ZipEntry 对象。 |
public class Decompressing
{
public static void main(String[] args)
{
File file = new File("hello.zip");
ZipInputStream zin;
try{
ZipFile zipFile = new ZipFile(file);
zin = new ZipInputStream(new FileInputStream(file));
ZipEntry entry = zin.getNextEntry();
while(((entry = zin.getNextEntry())!=null)&&!entry.isDirectory())
{
File tmp = new File("c:\\" + entry.getName());
if(!tmp.exits())
{
tmp.getParentFile().mkdirs();
OutputStream os = new FileOutputStream(tmp);
InputStream in = zipFile.getInputStream(entry);
int count = 0;
while((count=in.read())!=-1)
{
os.write(count);
}
os.close();
in.close();
}
zin.closeEntry();
System.out.println(entry.getName() + "解压成功");
}
zin.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
ZipFile 类。【补课】