超簡單的圖片下載
學習記錄
本文是根據img標籤的src屬性內的鏈接下載圖片
1.代碼如下
注意:下文中的path 路徑如無特別需求的情況下建議採用路徑+時間戳命名,
如一定要用絕對路徑+文件名命名的話,一定得要有一個圖片在文件內供替換/覆蓋才能下載成功要不然會報錯.
/**
* 鏈接url下載圖片
* 注:path 路徑一定要先有個圖片用來被替換,如用時間戳命名則不需要
* 如:img/" + System.currentTimeMillis() + ".png
*
*/
@org.junit.Test
public void imgDown() {
//圖片的src路徑
String srcUrl = "http://pic12.nipic.com/20110221/6727421_210944911000_2.jpg";
//將下載後的圖片保存在哪個路徑和命名成什麼名字,我這裏是將圖片下載在項目內的img文件內,並以時間戳命名
String path = "img/" + System.currentTimeMillis() + ".png";
URL url = null;
try {
url = new URL(srcUrl);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("圖片下載完成");
}
2.結果如下
1):圖片地址
2):下載完成後