标签:
Enumeration entries = zipFile.entries();//ZipFile为java.util.zip.ZipFile
while(entries.hasMoreElements()){
//do something
}
ZipEntry ze = (ZipEntry)entries.nextElement();
boolean b = ze.isDirectory();//是否是目录
String name = ze.getName();获取文件/文件夹名称
String name = new String(name.getBytes("8859_1"),"gb2312");//文件名转码
InputStream is = new BufferedInputStream(zipFile.getInputStream(ze));//从该节点获取输入流(输入到内存,ze必须不是目录)
zipFile.close();//关闭zip文件
/
分割节点名字符串(除了最后一个外均为路径)/**解压zip文件到指定路径*/
public static void unpackZipFile(ZipFile zipFile,String folderPath) {
Enumeration entries = zipFile.entries();
ZipEntry ze=null;
byte[] buf=new byte[1024];
//遍历节点
while (entries.hasMoreElements()){
ze= (ZipEntry) entries.nextElement();
//region 该节点是目录
if(ze.isDirectory()){
String dirstr= folderPath+ze.getName();//获取文件夹名称
try {
//创建文件夹
dirstr=new String(dirstr.getBytes("8859_1"),"gb2312");
File f=new File(dirstr);
f.mkdir();
}catch (Exception e){
e.printStackTrace();
}
continue;
}
//endregion
//region 该节点是文件
try {
//创建IO流复制文件
OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(folderPath, ze.getName())));
InputStream is = new BufferedInputStream(zipFile.getInputStream(ze));
int readLen=0;
while ((readLen=is.read(buf,0,1024))!=-1){
os.write(buf,0,readLen);
}
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
//endregion
}
//关闭文件
try {
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**根据相对路径获取并创建绝对路径*/
private static File getRealFileName(String baseDir,String absFileName){
String[] dirs=absFileName.split("/");//获取逐级相对路径
File ret=new File(baseDir);//用于记录每一级路径
String substr=null;
if(dirs.length>1) {
//循环遍历不包括最后一个节点,因为该节点不是路径,独立处理
for (int i = 0; i < dirs.length - 1; i++) {
substr = dirs[i];
try {
substr = new String(substr.getBytes("8859_1"), "gb2312");
} catch (Exception e) {
e.printStackTrace();
}
ret = new File(ret, substr);//记录该级路径
}
//创建每级目录
if (!ret.exists()) {
ret.mkdirs();
}
}
//处理最后一个节点
substr=dirs[dirs.length-1];
try{
substr=new String(substr.getBytes("8859_1"),"gb2312");
}catch (Exception e){
e.printStackTrace();
}
ret=new File(ret,substr);
if(!ret.exists()){
try {
ret.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
标签:
原文地址:http://blog.csdn.net/xmh19936688/article/details/51694502