JAVA URLConnection 实现下载小文件

使用URL对象的 URLConnection方法可以打开一个连接,然后可以通过InputStream获取字节流读取器

因为文件本身也是字节流,我们再创建一个文件流的写入器,即OutputStream对象,通过文件名来创建,然后把InputStream的内容写入到OutputStream中即可

对于文件以什么后缀名存放,需要通过URLConnection对象的getContentType方法,获得文件的类别,后缀名,这样方便我们命名

值得注意的是,写入发生在文件流的关闭之后,别忘了关闭OutputStream

import java.util.*;
import java.net.*;
import java.io.*;

public class Downloader {
	
	URL url;
	
	public void setURL(String u) throws Exception {
		url = new URL(u);
	}
	
	Downloader(String u) throws Exception {
		url = new URL(u);
	}
	
	Downloader()  {
		
	}
	
	public void getResources(String savePath, String fileName) throws Exception {
		// 建立连接对象
		URLConnection con = url.openConnection();
		con.connect();
		
		// 获取并拆分资源的类别名
		String type_tname = con.getContentType();
		String[] t = type_tname.split("/");
		String type=t[0], tname=t[1];
		System.out.printf("获取了 .%s 类型文件\n\n", tname);
		
		// 获取输入输出流
		InputStream is = con.getInputStream();
		FileOutputStream os = new FileOutputStream(savePath+fileName+"."+tname);
		
		// 写入文件流,缓存为10MB
		byte[] buf = new byte[10241024];
		int len;
		while((len=is.read(buf)) != -1) {
			os.write(buf, 0, len);
		}
		os.close();
	}
	
	public static void main(String[] args) throws Exception {
		/*
			https://www.baidu.com
			https://www.baidu.com/img/bd_logo1.png
		*/
		String save_path = "E:/MyEclipse/WorkSpace/Hello/src/lab5/downloadfiles/";
		String url, fileName;
		Downloader dl = new Downloader();
		Scanner scanner = new Scanner(System.in);
		
		while(true) {
			System.out.println("请输入:url  保存的文件名");
			url=scanner.next(); fileName=scanner.next();
			dl.setURL(url);
			dl.getResources(save_path, fileName);
		}
	}
}

在这里插入图片描述

下载成功!
在这里插入图片描述

html和png文件,可以正常打开
在这里插入图片描述

在这里插入图片描述

发布了262 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44176696/article/details/105473310
今日推荐