昨天在做一個項目時,用到了從服務器上下載文件并保存到本地的知識,以前也沒有接觸過,昨天搞了一天,這個小功能實現了,下面就簡單的說一下實現過程;
1.基礎知識
當我們想要下載網站上的某個資源時,我們會獲取一個url,它是服務器定位資源的一個描述,下載的過程有如下幾步:
(1)客戶端發起一個url請求,獲取連接對象。
(2)服務器解析url,并且將指定的資源返回一個輸入流給客戶。
(3)建立存儲的目錄以及保存的文件名。
(4)輸出了寫數據。
(5)關閉輸入流和輸出流。
2.實現代碼的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
/** * @功能 下載臨時素材接口 * @param filePath 文件將要保存的目錄 * @param method 請求方法,包括POST和GET * @param url 請求的路徑 * @return */ public static File saveUrlAs(String url,String filePath,String method){ //System.out.println("fileName---->"+filePath); //創建不同的文件夾目錄 File file= new File(filePath); //判斷文件夾是否存在 if (!file.exists()) { //如果文件夾不存在,則創建新的的文件夾 file.mkdirs(); } FileOutputStream fileOut = null ; HttpURLConnection conn = null ; InputStream inputStream = null ; try { // 建立鏈接 URL httpUrl= new URL(url); conn=(HttpURLConnection) httpUrl.openConnection(); //以Post方式提交表單,默認get方式 conn.setRequestMethod(method); conn.setDoInput( true ); conn.setDoOutput( true ); // post方式不能使用緩存 conn.setUseCaches( false ); //連接指定的資源 conn.connect(); //獲取網絡輸入流 inputStream=conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(inputStream); //判斷文件的保存路徑后面是否以/結尾 if (!filePath.endsWith( "/" )) { filePath += "/" ; } //寫入到文件(注意文件保存路徑的后面一定要加上文件的名稱) fileOut = new FileOutputStream(filePath+ "123.png" ); BufferedOutputStream bos = new BufferedOutputStream(fileOut); byte [] buf = new byte [ 4096 ]; int length = bis.read(buf); //保存文件 while (length != - 1 ) { bos.write(buf, 0 , length); length = bis.read(buf); } bos.close(); bis.close(); conn.disconnect(); } catch (Exception e) { e.printStackTrace(); System.out.println( "拋出異常!!" ); } return file; } |
3.代碼測試類(主函數)
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * @param args */ public static void main(String[] args) { String photoUrl = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png" ; String fileName = photoUrl.substring(photoUrl.lastIndexOf( "/" )); //System.out.println("fileName---->"+fileName); String filePath = "d:" ; File file = saveUrlAs(photoUrl, filePath + fileName, "GET" ); System.out.println( "Run ok!/n<BR>Get URL file " + file); } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/you18131371836/article/details/72790202