欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java压缩文件ZIP实例代码

程序员文章站 2024-02-20 14:29:52
提示:java.util.zipoutputstream         java api压缩为zi...

提示:java.util.zipoutputstream

        java api压缩为zip文件

代码:

复制代码 代码如下:

package com.gaoqi.test;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.util.zip.zipentry;
import java.util.zip.zipoutputstream;
/**
* 压缩文件
* @author administrator
*
*/
public class simplezip {

public static final int buffer_size = 1024;

public static void main(string[] args) throws ioexception {
string src = "d:\\chat";
string des = "d:\\chat01.zip";
zipoutputstream zos = null;
try{
zos = new zipoutputstream(new fileoutputstream(des));
file srcfile = new file(src);
string base = srcfile.getname();
filezip(srcfile,zos,base);
}catch (exception e) {
// todo: handle exception
e.printstacktrace();
}finally{
if(zos!=null){
zos.close();
}
}
system.out.println("文件压缩成功啦" + src);
}

private static void filezip(file srcfile, zipoutputstream zos, string base)
throws exception{
// todo auto-generated method stub
if(!srcfile.exists()){
system.out.println("文件不存在" + srcfile.getpath());
}
if(srcfile.isfile()){
zos.putnextentry(new zipentry(base));
fileinputstream fis = new fileinputstream(srcfile);
byte[] buf = new byte[buffer_size];
int n=0;
while((n=fis.read(buf, 0, buf.length))!=-1){
zos.write(buf, 0, n);
}
fis.close();
}else{
if(srcfile.isdirectory()) {
base = base + file.separator;
file[] subfiles = srcfile.listfiles();
for (file subfile : subfiles) {
filezip(subfile, zos, base + subfile.getname());
}
}
}
}
}