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