現(xiàn)成的圖片下載類,拿來(lái)就能用
class DownloadImage {
/**
* @param args
* @throws Exception
*/
public static void download(String urlString, String filename, String savePath) throws Exception {
// 構(gòu)造URL
URL url = new URL(urlString);
// 打開(kāi)連接
URLConnection con = url.openConnection();
// 設(shè)置請(qǐng)求超時(shí)為5s
con.setConnectTimeout(5 * 1000);
// 輸入流
InputStream is = con.getInputStream();
// 1K的數(shù)據(jù)緩沖
byte[] bs = new byte[1024];
// 讀取到的數(shù)據(jù)長(zhǎng)度
int len;
// 輸出的文件流
File sf = new File(savePath);
if (!sf.exists()) {
sf.mkdirs();
}
OutputStream os = new FileOutputStream(sf.getPath() + "\\" + filename);
// 開(kāi)始讀取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完畢,關(guān)閉所有鏈接
os.close();
is.close();
}
}