package com.bonc.wechat.common.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
/**
* 根據URL下載圖片到本地指定目錄!
*
* @author Administrator
*
*/
public class DownLodeImgsUtil {
/**
* 傳遞圖片的url,將圖片下載在對應的文件中
*
* @param urlString
* 圖片連接
* @param localAdd
* 下載到硬盤位置
* @param imgname
* 下載的圖片重命名名字
* @author xvk
* @throws Exception
*/
public static void downloadPhotos(String urlString, String localAdd,
String imgname) throws Exception {
File dir = new File(localAdd);
if (!dir.exists()) {
dir.mkdirs();
}
try {
File file = new File(localAdd + "/" + imgname);
OutputStream os = new FileOutputStream(file);
// 創建一個url對象
URL url = new URL(urlString);
InputStream is = url.openStream();
byte[] buff = new byte[1024];
while (true) {
int readed = is.read(buff);
if (readed == -1) {
break;
}
byte[] temp = new byte[readed];
System.arraycopy(buff, 0, temp, 0, readed);
// 寫入文件
os.write(temp);
}
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Test
public void testDownLodeImgsUnit() throws MalformedURLException{
String imgURL = "https://img.alicdn.com/bao/uploaded/i4/TB1.BpXOFXXXXbzXFXXXXXXXXXX_!!0-item_pic.jpg_430x430q90.jpg";
String imgname = "aaaaaaaaaa.jpg";
String localAdd = "D:\\imgs\\";
try {
DownLodeImgsUtil.downloadPhotos(imgURL, localAdd, imgname);
} catch (Exception e) {
e.printStackTrace();
}
}