使用java语言爬取网络图片并下载到本地

来源:互联网 发布:迷彩加厚羽绒服淘宝 编辑:程序博客网 时间:2024/06/07 13:02

我们经常会在网络上浏览到很多图片,有时候会想要下载下来。这次就尝试着用java代码把图片给下载到电脑上。

先下载一张图片试试。

图片的链接是:http://img03.sogoucdn.com/app/a/100520093/3c28af542f2d49f7-8331c86ff317d9f5-8ee52078d03feac9b8502dad26f33c31.jpg

要下载的图片为:


以下代码为下载此图片的代码(完整代码,经测试):

import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;public class Test {public static InputStream inStream = null;public static void main(String[] args){try {//要访问的图片链接URL url = new URL("http://img03.sogoucdn.com/app/a/100520093/3c28af542f2d49f7-8331c86ff317d9f5-8ee52078d03feac9b8502dad26f33c31.jpg");//建立网络连接URLConnection con = url.openConnection();inStream = con.getInputStream();//中转站,现将图片数据放到outStream中ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buf = new byte[1024];int len = 0;while((len = inStream.read(buf)) != -1){outStream.write(buf,0,len);}inStream.close();outStream.close();File file = new File("f://a.jpg"); //图片下载的位置FileOutputStream op = new FileOutputStream(file);op.write(outStream.toByteArray());op.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
然后看下F盘下的内容:

这样表示下载完成了。

阅读全文
0 0