URL:通过connection下载资源

13 篇文章 0 订阅
2 篇文章 0 订阅
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/** 
* @author  万星明
* @version 创建时间:2018年10月26日 上午9:47:40 
*/
public class URLconnection下载 {
	public static void main(String[] args) throws Exception {
		
		
		
	}
	//方法一,采用网络读取流加BufferedOutputStream
	public static void way1() throws Exception {
		
		//创建url对象
		URL url = new URL("https://wenku.baidu.com/browse/downloadrec?doc_id=af07773acbaedd3383c4bb4cf7ec4afe04a1b18b&");
		//创建连接对象
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		//判断是否连接成功
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
			//创建网络读取流
			InputStream is = url.openStream();
			//创建本地写入流
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a.pdf"));
			//边读取边写入
			byte[] b = new byte[1024];
			int len = is.read(b);
			while(len!=-1) {
				bos.write(b,0,len);
				len = is.read(b);
			}
			System.out.println("下载成功");
			is.close();
			bos.close();
					
		}
	}
	
	//方法二,采用网络读取流加内存流ByteArrayOutputStream
	//采用ByteArrayOutputStream先将数据写入到内存中,然后再一次性写到目标文件中
	public static void way2() throws Exception {
		
		URL url = new URL("https://www.baidu.com/img/bd_logo1.png?where=super");
		//创建连接对象
		HttpURLConnection connection  = (HttpURLConnection) url.openConnection();
		//判断是否连接成功
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
			//创建网络读取流
			InputStream is = url.openStream();
			//创建本地写入流
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			byte[] b = new byte[1024];
			int len = is.read(b);
			while(len!=-1) {
				baos.write(len);
				len = is.read(b);
			}
			baos.writeTo(new FileOutputStream("a.png"));
			System.out.println("下载成功");
			is.close();
			baos.close();
		}
			
	}
	
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值