您的位置:首页 > 编程语言 > Java开发

用java下载一个网页图片

2014-06-11 10:07 369 查看
通过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 length
URLConnection 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
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: