提示: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());
}
}
}
}
}