//文件名中有中文会有错误
package unzip;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class newUnZip {
public static void main(String[] args) throws Exception {
newUnZip unzip = new newUnZip();
String zippath = "D://temp//";
String zipDir = "D://data//";
File file = new File(zipDir);
List<File> list = unzip.getSubFiles(file);
for (Object obj : list) {//获得文件列表
String realname = ((File) obj).getName();
unzip.ReadZip(zippath, zipDir + realname);
}
}
public void ReadZip(String zippath, String unzipPath) throws Exception {
ZipFile zfile = new ZipFile(unzipPath);// creat zip object
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[2048];
BufferedOutputStream os = null;
BufferedInputStream is = null;
/**
* get every file in zip file
*/
while (zList.hasMoreElements()) {
// get ZipEntry from ZipFile
ze = (ZipEntry) zList.nextElement();
//create directory
if (ze.isDirectory()) {
// File directory = new File(olddirec.getParent(), entry
// .getName());
File directory = new File("d://temp", ze
.getName());
if (!directory.exists())
if (!directory.mkdirs())
System.exit(0);
continue;
}
/****************************************/
is = new BufferedInputStream(zfile.getInputStream(ze));
os = new BufferedOutputStream(new FileOutputStream(getRealFileName(
zippath, ze.getName())));
int readLen = 0;
while ((readLen = is.read(buf, 0, 2048)) != -1) {
os.write(buf, 0, readLen);
}
os.flush();
os.close();
is.close();
}
zfile.close();
}
private File getRealFileName(String zippath, String absFileName) {
String[] dirs = absFileName.split("/", absFileName.length());
File ret = new File(zippath);
if (dirs.length > 0) {
for (int i = 0; i < dirs.length; i++) {
ret = new File(ret, dirs[i]);
}
}
return ret;
}
private List<File> getSubFiles(File baseDir) {
List<File> ret = new ArrayList<File>();
File[] tmp = baseDir.listFiles();
for (int i = 0; i < tmp.length; i++) {
if (tmp[i].isFile()) {
ret.add(tmp[i]);
}
if (tmp[i].isDirectory()) {
ret.addAll(getSubFiles(tmp[i]));
}
}
return ret;
}
}