java 下载网络图片并保存到本地
第一种
public static void downloadPicture(String urlList,String path) {
URL url = null;
try {
url = new URL(urlList);
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();
}
}
public static void main(String[] args) {
String baiduLogoUrl = "https://www.baidu.com/img/bd_logo1.png";
File localFile = new File("E:\\test\\" + "bd_logo1.png");
downloadPicture(baiduLogoUrl,"E:\\test\\bd_logo1.png");
}
第二种
public static void downloadImage(String imageUrl, String savePath) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10*1000);
InputStream stream = connection.getInputStream();
int len = 0;
byte[] test = new byte[1024];
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(savePath));
while ((len =stream.read(test)) !=-1){
fos.write(test,0,len);
}
stream.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}