1.压缩文件
利用ZipOutoutStream类对象,可将文件压缩为。zip文件。ZipOutputStream类的构造函数如下:
ZipOutputStream(OutputStream out);
ZipOutputStream类的常用方法:
putNextEntry(ZipEntry e):开始写一个新的ZipEntry,并且将流内的位置移至此entry所指数据的开头
write(byte[] b,int off,int len):将字节数组写入当前ZIP条目数据
finish():完成写入ZIP输出流的内容,无须关闭它所配合的OutputStream
setComment(String comment):可设置此ZIP文件的注释文字
2.解压ZIP文件
ZipInputStream类可读取ZIP压缩格式的文件,包括对已压缩和未压缩条目的支持(entry)。ZipInputStream类的构造函数:
ZipInputStream(InputStream in)
ZipInputStream类的常用方法:
read(byte[]b, int off,int len):读取目标b数组内off偏移量的位置,长度是len字节
available():判断是否已读完目前entry所指定的目标。读完返回0;否则返回1
closeEntry():关闭当前ZIP条目并定位流以读取下一个条目
skip(long n):跳过当前ZIP条目中指定的字节数
getNextEntry():读取下一个ZipEntry,并将流内的位置移至entry所指数据的开头
createZipEntry(String name):以指定的name参数新建一个ZipEntry对象
3.压缩所有子文件夹
public class 压缩 {
private void zipFile(List<String>path,File targetZipFile,String base) throws IOException{
FileOutputStream fos= new FileOutputStream(targetZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
byte[] buffer=new byte[1024];
for(String string:path){
File currentFile = new File(string);
ZipEntry entry = new ZipEntry(string.substring(base.length()+1,string.length()));
FileInputStream fis =new FileInputStream(currentFile);
zos.putNextEntry(entry);
int read=0;
while((read=fis.read(buffer))!=-1){
zos.write(buffer,0,read);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
}