JAVA基于网络的文件下载

基于UDP的文件下载

构建连接

首先我们需要获取所需的文件资源所在的地址,然后根据地址创建URL对象,再通过对象获取文件所在路径以及文件名,为后来的下载到本机做好准备。
同时获取到文件的输出流。
(last.indexof("/") 获取“”/“”最后一次出现的位置)
target是定义好的参数,是下载的目标文件名。

URL url1 = new URL(url);
			String path = url1.getPath();
			int index = path.lastIndexOf("/");
			String fname = path.substring(index+1);
			target = new File(target, fname);
			
			OutputStream os = new FileOutputStream(target);

根据创建好的URL对象建立连接(openConnection()),然后判断连接是不是好的,是的话开启下载任务。
下载使用到了流的知识,获取到连接的输入流开始下载

HttpURLConnection conn = null;
				try {
					conn = (HttpURLConnection)url1.openConnection();
					conn.setRequestMethod("GET");
					int statecode = conn.getResponseCode();
					if (statecode == HttpURLConnection.HTTP_OK) {
						InputStream is = conn.getInputStream();
						byte[] b =new byte[1024];
						int len =0;
						while ((len = is.read(b)) != -1) {
							os.write(b, 0, len);
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					try {
						os.close();
						conn.disconnect();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

try里的异常请捕获,不要抛出。

测试

选开始测试需要的网址,下面是全部代码,网址自选,因为这是一个耗时的项目,所以我们采用线程来减少消耗。

public void download(String url, File target) throws MalformedURLException, FileNotFoundException {
			URL url1 = new URL(url);
			String path = url1.getPath();
			int index = path.lastIndexOf("/");
			String fname = path.substring(index+1);
			target = new File(target, fname);
			
			OutputStream os = new FileOutputStream(target);
			
			new Thread(()->{
				HttpURLConnection conn = null;
				try {
					conn = (HttpURLConnection)url1.openConnection();
					conn.setRequestMethod("GET");
					int statecode = conn.getResponseCode();
					if (statecode == HttpURLConnection.HTTP_OK) {
						InputStream is = conn.getInputStream();
						byte[] b =new byte[1024];
						int len =0;
						while ((len = is.read(b)) != -1) {
							os.write(b, 0, len);
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					try {
						os.close();
						conn.disconnect();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}).start();
			
	}
	
	public static void main(String[] args) throws MalformedURLException, FileNotFoundException {
		new FileDownload().download("http://*****.*******.***/musics/1592383934192.mp3", new File("f:\\"));
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值