java实现zip文件解压有两种方式,一种是jdk提供的工具包java.util.zip,但不支持设置编码格式,如果解压的文件有中文,就可能出现乱码,这里推荐使用第三方org.apache.tools.zip工具类
引入依赖或者手动导入jar包
**注意:**jdk7只能使用1.9.x以下版本,jdk8可以使用2.0.x以上版本
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.9</version>
</dependency>
zipUtil工具类
public class ZipUtil {
private static byte[] _byte = new byte[1024] ;
public static List<String> upZipFile(File zipFile, String descDir) {
List<String> _list = new ArrayList<String>();
try {
ZipFile _zipFile = new ZipFile(zipFile);
for (Enumeration entries = _zipFile.getEntries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String fileDestName = descDir + entry.getName();
if (!descDir.endsWith("/")) {
fileDestName = descDir + "/" + entry.getName();
}
File _file = new File(fileDestName);
if (entry.isDirectory()) {
_file.mkdirs();
} else {
File _parent = _file.getParentFile();
if (!_parent.exists()) {
_parent.mkdirs();
}
InputStream _in = _zipFile.getInputStream(entry);
OutputStream _out = new FileOutputStream(_file);
int len;
while ((len = _in.read(_byte)) > 0) {
_out.write(_byte, 0, len);
}
if (null != _out) {
_out.flush();
_out.close();
}
if (null != _in) {
_in.close();
}
_list.add(fileDestName);
}
}
_zipFile.close();//必须关闭才能删除zip文件,linux服务器删除成功,但是本地zip文件没有删除,没有研究为什么
} catch (IOException ex) {
ex.printStackTrace();
}
return _list ;
}
}