/**
* 给定一个zip的url,实现zip的下载.下载到目的文件夹
* id为用户给定的id,方便维护
* <p>
* 返回zip文件的最终文件路径
*/
public static String downloadZIP(String[] UrlAndZipName, String fileDisDir) throws Exception {
String strUrl = UrlAndZipName[0];
String fileName = UrlAndZipName[1];
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
conn.connect();
InputStream inStream = conn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = inStream.read(buf)) != -1) {
outStream.write(buf, 0, len);
}
inStream.close();
outStream.close();
String zippath = fileDisDir + File.separator + fileName + ".zip";
File file = new File(zippath);
FileOutputStream op = new FileOutputStream(file);
op.write(outStream.toByteArray());
op.close();
return zippath;
}
/**
* 解压文件到指定目录
* 解压后的文件名,和之前一致
* <p>
* 返回最终解压的文件夹路径
*/
public static String unZipFiles( String zipFilePath, String descDir) throws IOException {
File zipFile=new File(zipFilePath);
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));//解决中文文件夹乱码
String name = zip.getName().substring(zip.getName().lastIndexOf('\\')+1, zip.getName().lastIndexOf('.')); //此处的\\针对windows,在linux用 / ,推荐改成File.sepator
File pathFile = new File(descDir+ File.separator+name);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir +File.separator+ name +File.separator+ zipEntryName).replaceAll("\\*", "/");
// 判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
// 输出文件路径信息
// System.out.println(outPath);
FileOutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
System.out.println("******************解压完毕********************");
return (descDir+ File.separator+name);
}