Posted on 2009-10-30 22:28
xcp 閱讀(3297)
評論(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: 聯系我