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文件,可以正常打開
在這裏插入圖片描述

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章