作者:月亮哥哥是团宠他男人 | 来源:互联网 | 2023-09-25 13:55
package test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
/**
* zip解压程序
*/
public class test3 {
public static void main(String[] args) throws Exception {
//要解压的目录
File file = new File("F:\\java\\");
//ZipFile是ant.jar里面的对象
ZipFile zipFile = new ZipFile("F:\\java\\xmlobj.rar","GBK");
Enumeration en = zipFile.getEntries();
//ZipEntry是ant.jar里面的对象
ZipEntry zipEntry = null;
try {
while (en.hasMoreElements()) {
boolean isExist = true;//文件和文件夹是否存在
zipEntry = (ZipEntry) en.nextElement();
if (zipEntry.isDirectory()) {//如果是目录
String dirName = zipEntry.getName();
dirName = dirName.substring(0, dirName.length() - 1);
File f = new File(file.getPath() + File.separator + dirName);
f.mkdirs();
} else {
String strFilePath = file.getPath() + File.separator
+ zipEntry.getName();
File f = new File(strFilePath);
// 判断文件不存在的话,就创建该文件所在文件夹的目录
if (!f.exists()) {
isExist = false;
String[] arrFolderName = zipEntry.getName().split("/");
String strRealFolder = "";
for (int i = 0; i <(arrFolderName.length - 1); i++) {
strRealFolder += arrFolderName[i] + File.separator;
}
strRealFolder = file.getPath() + File.separator
+ strRealFolder;
File tempDir = new File(strRealFolder);
// 此处使用.mkdirs()方法,而不能用.mkdir()
tempDir.mkdirs();
}
//创建文件
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
try {
int c;
byte[] by = new byte[1024];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
out.flush();
} catch (IOException e) {
throw e;
} finally {
out.close();
in.close();
}
}
}
} catch (IOException e) {
throw e;
}finally{
zipFile.close();
}
}
}
ant.jar下载