使用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文件,可以正常打开