Posted on 2009-10-30 22:28
xcp 阅读(3292)
评论(2) 编辑 收藏 所属分类:
JAVA
前面写了一篇,java 压缩文件 ZipOutputStream 支持中文,同样java提供的java.util.zip.*.......对中文不支持面就是一个简单的例子,注 需要导入ant.jar支持包.
package cn.edu.cuit.disasterSystem.web.struts2.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
/**
* 采用org.apache.tools.zip来进行zip包的解压缩,支持目录嵌套和中文名
* @author xcp
* @version 1.0 Copyright (C), 2009 智能开发实验室 所有 Program Name:灾情信息管理系统
* Date: 2009-10-28 下午09:05:13
*/
public class CompressFromZip {
private void createDirectory(String directory, String subDirectory) {
String dir[];
File fl = new File(directory);
try {
//如果解压文件基本目录结构不存在,新建
if (subDirectory == "" && fl.exists() != true){
//System.out.println("*******创建基本目录结构*******"+directory);
fl.mkdir();
}
//主要创建子目录
else if (subDirectory != "") {
dir = subDirectory.replace('\\', '/').split("/");
for (int i = 0; i < dir.length; i++) {
File subFile = new File(directory + File.separator + dir[i]);
if (subFile.exists() == false){
//System.out.println("*******创建子目录*******"+directory + File.separator + dir[i]);
subFile.mkdir();
}
directory += File.separator + dir[i];
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
@SuppressWarnings("unchecked")
public void unZip(String zipFileName, String outputDirectory)
throws Exception {
try {
org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName);
java.util.Enumeration e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
while (e.hasMoreElements()) {
zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
System.out.println("========== 解压 ========== " + zipEntry.getName());
//判断是否为一个文件夹
if (zipEntry.isDirectory()) {
String name = zipEntry.getName().trim();
//因为后面带有一个/,所有要去掉
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
if(!f.exists()){
f.mkdir();
}
//System.out.println("*******创建根目录*******" + outputDirectory + File.separator + name);
} else {
String fileName = zipEntry.getName();
fileName = fileName.replace('\\', '/');
//判断子文件是否带有目录,有创建,没有写文件
if (fileName.indexOf("/") != -1){
createDirectory(outputDirectory, fileName.substring(0,fileName.lastIndexOf("/")));
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
}
File f = new File(outputDirectory + File.separator + zipEntry.getName());
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
in.close();
out.close();
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("^^^^^^^^^^ 解压完成 ^^^^^^^^^^");
}
public static void main(String[] args) {
CompressFromZip test = new CompressFromZip();
try {
test.unZip("d:\\批量打包.zip", "d:\\temp");
} catch (Exception e) {
e.printStackTrace();
}
}
}
名称: ♪4C.ESL | .↗Evon
口号: 遇到新问题♪先要寻找一个方案乄而不是创造一个方案こ
mail: 联系我