java zip压缩

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;


public class ZipTest {
private static String root;


public static void zipFile(File file) {
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(new File


("E:\\桌面\\"
+ file.getName() + ".zip")));
zipFile(file, out);


} catch (Exception e) {
System.out.println("出现异常");
} finally {
if (out != null) {
try {
out.finish();
} catch (IOException e) {
}
}
}
}


public static void zipFile(File file, ZipOutputStream out) throws 


Exception {
String path = file.getPath();
int index = path.lastIndexOf(root) + root.length();
if (file.isDirectory()) {
File[] subFile = file.listFiles();
for (File f : subFile) {
zipFile(f, out);
}
} else {
zipFile(file, path.substring(index + 1), out);
}
}


public static void zipFile(File file, String zipPath, ZipOutputStream 


out)
throws Exception {
if (file.isDirectory()) {
out.putNextEntry(new ZipEntry(zipPath + "/" + 


file.getName() + "/"));
} else {
out.putNextEntry(new ZipEntry(zipPath));
FileInputStream in = new FileInputStream(file);
byte[] b = new byte[1000];
int len = -1;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
in.close();
}
}


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("E:\\桌面\\乱七八糟");
if (file.exists()) {
try {
root = file.getName();
zipFile(file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("文件不存在!!!");
}


}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值