把指定目錄下面的所有文件壓縮成一個ZIP

今天項目中用到了將word壓縮成zip文件供用戶下載,特記下以後備用


/**
* function:把指定目錄下面的所有文件壓縮成一個ZIP
* creator:morris
* create date:2009/05/31
* updater:
* update date:
*/

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipFile {

private String destinationDir = null; // zip file dir
private String fileName = null; // zip file name
private ZipOutputStream zout; // zip class
private ZipInputStream zin;

public ZipFile(String temp1,String temp2){
this.destinationDir = temp1;
this.fileName=temp2;
}

public void newZip() throws FileNotFoundException {
File temp=new File(this.destinationDir);
temp.mkdirs();
zout =
new ZipOutputStream(
new FileOutputStream(
this.destinationDir + "\\" + this.fileName));
}

//首先刪除該文件夾下所有文件
public void deleteAllFile(File tempDir) throws Exception {
File temp_file[] = null;
temp_file = tempDir.listFiles();
for (int i = 0; i < temp_file.length; i++) {
if (temp_file[i].isFile()) {
temp_file[i].delete();
}
}
}

//壓縮文件夾下面的所有文件為ZIP文件
public void createZipFile(File tempDir) throws Exception {
File temp_file[] = null;
byte temp[] = new byte[512];
temp_file = tempDir.listFiles();
for (int i = 0; i < temp_file.length; i++) {
if (temp_file[i].isFile()) {
FileInputStream in = new FileInputStream(temp_file[i]);
String temp1=new String(temp_file[i].getAbsolutePath().getBytes("ISO8859-1"));
if(!temp1.endsWith("zip")){
ZipEntry zip =
new ZipEntry(temp_file[i].getName());
zout.putNextEntry(zip);
int len = 0;
while ((len = in.read(temp)) != -1) {
zout.write(temp, 0, len);
}
zout.closeEntry();
}
}else{
createZipFile(temp_file[i]);
}
}
}

public void closeZip() throws Exception{
this.zout.close();
}

public void getZipFile(File tempDir){
try{
this.newZip();
this.createZipFile(tempDir);
this.closeZip();
}catch(Exception e){
e.printStackTrace();
}
}

//解壓ZIP文件
public void refreshZipFile() throws Exception{
ZipEntry temp=null;
FileOutputStream temp_file=null;
byte btemp[]=new byte[256];
zin=new ZipInputStream(new FileInputStream(this.destinationDir + "\\" + this.fileName));
while((temp=zin.getNextEntry())!=null){
File local=new File((new File(temp.getName())).getParent());
local.mkdirs();
temp_file=new FileOutputStream(temp.getName());
while(zin.read(btemp)!=-1){
temp_file.write(btemp);
}
temp_file.close();
zin.closeEntry();
}
zin.close();
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值