根据图片的URL将其下载到本地
转载自: http://hi.baidu.com/xuewei2099/item/f31c1e8634c967c7ee083db4
Problem Remained:在保证网速的情况下,如何通过算法设计加速网络连接,缩短下载时间?
转载自: http://hi.baidu.com/xuewei2099/item/f31c1e8634c967c7ee083db4
Problem Remained:在保证网速的情况下,如何通过算法设计加速网络连接,缩短下载时间?
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* 使用URLConnection下载文件或图片并保存到本地。
*
* @author 老紫竹(laozizhu.com)
*/
public class URLConnectionDownloader {
public static void main(String[] args) throws Exception {
download("http://www.url.com/image.jpg", "image.jpg");
}
public static void download(String urlString, String filename) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
OutputStream os = new FileOutputStream(filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
将照片下载保存到对应的文件夹中:http://blog.youkuaiyun.com/willproud/article/details/8873365