解压文件无非就是这几个步骤:
1.指定要解压文件的位置和解压后文件或是文件夹的位置
2.列出压缩文件中所有的文件或是文件夹
3.如果是文件,则读取。如果是文件夹,则创建。
以下为实例代码:
public static void unzip(String zipFilePath, String targetPath)
throws IOException {
OutputStream os = null;
InputStream is = null;
ZipFile zipFile = null;
try {
//1.获取要解压的文件 , 并指定解压格式为“GBK”
zipFile = new ZipFile(zipFilePath, Charset.forName("GBK"));
//读取zip文件中每一个文件及文件夹
Enumeration<?> entryEnum = zipFile.entries();
if (null != entryEnum) {
ZipEntry zipEntry = null;
//总共有多少文件或是文件夹就循环多少次
while (entryEnum.hasMoreElements()) {
//获取下一个文件或者文件夹
zipEntry = (ZipEntry) entryEnum.nextElement();
if (zipEntry.getSize() > 0) {
// 文件 File.separator就是“/”
File targetFile = new File(targetPath
+ File.separator + zipEntry.getName());
//将文件读取到指定文件位置
os = new BufferedOutputStream(new FileOutputStream(targetFile));
is = zipFile.getInputStream(zipEntry);
byte[] buffer = new byte[4096];
int readLen = 0;
while ((readLen = is.read(buffer, 0, 4096)) >= 0) {
os.write(buffer, 0, readLen);
os.flush();
}
is.close();
os.close();
}
//如果是文件夹,则创建文件夹
if (zipEntry.isDirectory()) {
String pathTemp = targetPath + File.separator
+ zipEntry.getName();
File file = new File(pathTemp);
file.mkdirs();
}
}
}
} catch (IOException ex) {
throw ex;
} finally {
//关闭流
if (null != zipFile) {
zipFile.close();
zipFile = null;
}
if (null != is) {
is.close();
}
if (null != os) {
os.close();
}
}
}