您的位置:首页 > 理论基础 > 计算机网络

java网络编程:下载网络上的一张图片

2011-07-20 10:42 423 查看
1:ImageRequest 类
package com.capinfotech.net;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageRequest {

public static void main(String[] args) throws IOException {
URL url = new URL("http://www.eoeandroid.com/data/attachment/forum/201107/18/142935bbi8d3zpf3d0dd7z.jpg");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream inputStream = conn.getInputStream();   //通过输入流获得图片数据
byte[] getData = readInputStream(inputStream);     //获得图片的二进制数据

File imageFile = new File("capinfotech.png");
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(getData);
fos.close();

System.out.println(" read picture success");
}

public static  byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}

bos.close();
return bos.toByteArray();
}
}

2:测试结果: 图片下载到项目的src目录下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: