用流的方式在实现对网络图片的下载
分析:
参数:
图片的网络地址:webURL
保存到本地地址:localPath
监听器:判断是否下载成功(这是一个观察者模式)
具体代码如下:
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
/**
* @author test
*/
public class DownLoadPicture {
public static void main(String[] args) {
//网络图片链接地址
String webURL = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1468179265,2584742085&fm=26&gp=0.jpg";
//本地保存地址
String localPath = "D:\\test\\picture.jpg";
downLoadJpg(webURL, localPath);
}
public static void downLoadJpg(String webURL, String localPath) {
try {
//网络URL
URL url = new URL(webURL);
//打开网络连接
URLConnection connection = url.openConnection();
//输入流
InputStream inputStream = connection.getInputStream();
//输出文件流
OutputStream outputStream = new FileOutputStream(new File(localPath));
//缓冲区对象
byte[] b = new byte[1024];
//读取计数器
int len;
while ((len = inputStream.read(b)) != -1) {
outputStream.write(b, 0, len);
}
//关闭输入流操作
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
//关闭输出流操作
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
//监听下载成功
} catch (Exception e) {
//监听下载失败
e.printStackTrace();
}
}
}