/**
* 給定一個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);
}