下载网络图片

140 篇文章 7 订阅
116 篇文章 22 订阅

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

package com.home;

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

public class DownloadImage {
	public DownloadImage() {
		try {
			getImage();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new DownloadImage();
	}

	/**
	 * 读取网络图片
	 * 
	 * @throws Exception
	 */
	public void getImage() throws Exception {
		// 图片url路劲
		String urlpath = "http://pica.nipic.com/2008-05-23/200852381811521_2.jpg";
		// 建立URL对象,抛出异常
		URL url = new URL(urlpath);
		// 得到HttpURLConnection对象
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 声明请求方式
		conn.setRequestMethod("GET");
		// 设置连接超时
		conn.setConnectTimeout(6 * 1000);
		// 连接成功
		if (conn.getResponseCode() == 200) {
			// 得到服务器传回来的数据,相对我们来说输入流
			InputStream inputStream = conn.getInputStream();
			// 得到数据
			byte[] data = readInStream(inputStream);
			// 创建保存文件
			File file = new File("C:/image.jpg");
			// 创建一个文件输出流
			FileOutputStream outputStream = new FileOutputStream(file);
			// 将我们所得的二进制数据全部写入我们建好的文件中
			outputStream.write(data);
			// 关闭输出流
			outputStream.close();
		}

	}

	/**
	 * 读取流文件的内容
	 * 
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
	public byte[] readInStream(InputStream inputStream) throws Exception {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 声明缓冲区
		byte[] buffer = new byte[1024];
		// 定义读取默认长度
		int length = -1;
		while ((length = inputStream.read(buffer)) != -1) {
			// 把缓冲区中输出到内存中
			byteArrayOutputStream.write(buffer, 0, length);
		}
		// 关闭输出流
		byteArrayOutputStream.close();
		// 关闭输入流
		inputStream.close();
		// 返回这个输出流的字节数组
		return byteArrayOutputStream.toByteArray();
	}
}


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

u010142437

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值