用java下载一个网页图片

来源:互联网 发布:无间道3 知乎 编辑:程序博客网 时间:2024/05/18 01:09

通过java URL类来实现下载一个网页目标。

URL常用方法

URLConnection openConnection()
          返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。

可通过返回的URLConnection获取文件大小等信息

InputStream openStream()
          打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream

代码如下:

import java.net.*;import java.io.*;public class Net0611 {public void init() throws IOException{URL url = new URL("http://cms.csdnimg.cn/article/201406/10/53963e4f52b62.jpg");//get lengthURLConnection uc = url.openConnection();int len = uc.getContentLength();InputStream in = null;RandomAccessFile rf = null;try{in = url.openStream();rf = new RandomAccessFile("net0611.jpg","rw");byte[] buff = new byte[64];int getlen = 0;while(getlen < len){int readlen = (len-getlen) > 64 ? 64 : (len-getlen);int ret = in.read(buff, 0, readlen);rf.write(buff, 0, ret);getlen += ret;}}catch (Exception e){e.printStackTrace();}finally{try{if(in != null)in.close();if(rf != null)rf.close();}catch(Exception e){e.printStackTrace();}}//creat file//write}}


0 0