InputStream ism = null;
try{
URL imgUrl = new URL(url);
//获得资源,获得失败时重试,最多三次
int x = 1;
while (true) {
try {
ism = imgUrl.openStream();
break;
} catch (IOException e) {
continue;
} finally {
if (x >= 3) break;
x++;
}
}
//若资源获得成功开始保存
if(ism!=null){
OutputStream osm = new FileOutputStream(dir);
byte[] buff = new byte[1024];
while (true) {
int readed = ism.read(buff);
if (readed == -1) {
break;
}
byte[] temp = new byte[readed];
System.arraycopy(buff, 0, temp, 0, readed);
osm.write(temp);
}
osm.close();
}
}catch(Exception e){
e.printStackTrace();
}