Android 学习 笔记_05. 文件下载
文件下載的步驟:
? 1、創(chuàng)建一個(gè)HttpURLConnection對象
? ? ? ? ? ??HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
? 2、獲得一個(gè)InputStream()對象 ??
? ? ? ? ? ? urlConn.getInputStream();
? 3、訪問網(wǎng)路的權(quán)限
? ? ? ? ? ?android.permission.INTERNET
? ?現(xiàn)做一個(gè)小程序如下,能夠下載文本文件和Mp3文件
? ? ? ? ? ? ? ? ? ? ? ?
?main.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:orientation="vertical" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 tools:context=".Download_Activity" > 7 8 <Button 9 android:layout_width="fill_parent" 10 android:layout_height="wrap_content" 11 android:id="@+id/downloadText" 12 android:text="@string/downloadTextButton"/> 13 <Button 14 android:layout_width="fill_parent" 15 android:layout_height="wrap_content" 16 android:id="@+id/downloadMp3" 17 android:text="@string/downloadMp3Button"/> 18 </LinearLayout>Download_Activity.java
1 package zzl.download; 2 3 import zzl.utils.HttpDownload; 4 import android.app.Activity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 10 public class Download_Activity extends Activity { 11 12 private Button downloadMp3Button; 13 private Button downloadTextButton; 14 @Override 15 public void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.main); 18 downloadMp3Button=(Button)findViewById(R.id.downloadMp3); 19 downloadTextButton=(Button)findViewById(R.id.downloadText); 20 downloadMp3Button.setOnClickListener(new DownloadMp3Listener()); 21 downloadTextButton.setOnClickListener(new DownloadTextListener()); 22 } 23 class DownloadTextListener implements OnClickListener{ 24 25 @Override 26 public void onClick(View v) { 27 // TODO Auto-generated method stub 28 HttpDownload httpDownloader=new HttpDownload(); 29 String lrc =httpDownloader.download("http://photo.weibo.com/152611965/wbphotos/large/photo_id/3549709337146075?refer=weibofeedv5"); 30 System.out.println(lrc); 31 } 32 } 33 class DownloadMp3Listener implements OnClickListener{ 34 35 @Override 36 public void onClick(View v) { 37 // TODO Auto-generated method stub 38 HttpDownload httpDownloader=new HttpDownload(); 39 int result =httpDownloader.downloadFile("http://photo.weibo.com/152611965/wbphotos/large/photo_id/3549709337146075?refer=weibofeedv5","photo_id/","3549709337146075?refer=weibofeedv5"); 40 System.out.println(result); 41 } 42 } 43 44 }?
HttpDownload.java
1 package zzl.utils; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.InputStreamReader; 8 import java.net.HttpURLConnection; 9 import java.net.URL; 10 11 12 /*前提:首先判斷所下載的文件是否為純文本文件 13 * 1.創(chuàng)建一個(gè)URL對象 14 * 2.通過URL對象獲取HttpOpenConnection對象(代表和網(wǎng)絡(luò)上的http對象的連接) 15 * 3.獲取InputStream對象 16 * 4.讀取數(shù)據(jù) 17 * 5.將讀取的數(shù)據(jù)寫入SD卡 18 * */ 19 public class HttpDownload { 20 private URL url = null; 21 22 //下載任何形式 的文本文件 23 public String download(String urlStr){ 24 StringBuffer sb = new StringBuffer(); 25 String line = null; 26 BufferedReader bufr = null; 27 28 try { 29 // 創(chuàng)建一個(gè)URL對象:調(diào)用URL函數(shù),將地址傳入 30 url = new URL(urlStr); 31 //通過URL創(chuàng)建一個(gè)HTTP連接 32 HttpURLConnection con = (HttpURLConnection)url.openConnection(); 33 //使用IO流讀取數(shù)據(jù),這里使用到了轉(zhuǎn)換流,提高讀取效率 【【 字節(jié)流轉(zhuǎn)換成字符流再轉(zhuǎn)換成讀取行數(shù)據(jù)】】 34 bufr = new BufferedReader(new InputStreamReader(con.getInputStream())); 35 while((line = bufr.readLine())!=null){ 36 sb.append(line); 37 } 38 39 } catch (Exception e) { 40 System.out.println("文本文件下載失敗!"); 41 e.printStackTrace(); 42 }finally{ 43 if(bufr!=null) 44 try { 45 bufr.close(); 46 } catch (IOException e) { 47 System.out.println("文本文件讀取流關(guān)閉失敗!"); 48 e.printStackTrace(); 49 } 50 } 51 return sb.toString(); 52 53 } 54 //訪問SD卡 55 /* 1.得到當(dāng)前設(shè)備SD卡的目錄 56 * Environment.getExternalStorageDirectory() 57 * */ 58 //可下載各種文件 59 //返回 -1:代表下載文件出錯(cuò) 返回0:代表下載文件成功 返回 1:代表文件已經(jīng)存在 60 //fileName代表你將要存入SD卡中的文件名,可以定義自己的文件名 61 public int downloadFile(String url,String path,String fileName){ 62 InputStream in = null; 63 try { 64 File_Utils utils = new File_Utils() ; 65 //如果存在該文件了則返回1 66 if(utils.isFileExist(path+fileName)){ 67 return 1; 68 }else{//否則則就獲得否則則就通過調(diào)用File_Utils.java的write2SDFromInputStream函數(shù)寫入SD卡中 69 in = getInputStreamFromUrl(url); 70 File resultFile = utils.write2SDFromInputStream(path, fileName, in); 71 if(resultFile == null){ 72 return -1; 73 } 74 } 75 76 } catch (IOException e) { 77 e.printStackTrace(); 78 return -1; 79 }finally{ 80 if(in!=null){ 81 try { 82 in.close(); 83 } catch (IOException e) { 84 System.out.println("字節(jié)讀取流關(guān)閉失敗!"); 85 e.printStackTrace(); 86 } 87 } 88 } 89 return 0; 90 } 91 92 //將根據(jù)URL獲取InputStream的功能封裝起來,以便復(fù)用 93 public InputStream getInputStreamFromUrl(String urlStr) throws IOException{ 94 url = new URL(urlStr); 95 HttpURLConnection con = (HttpURLConnection) url.openConnection(); 96 InputStream in = con.getInputStream(); 97 return in; 98 } 99 }File_Utils.java
1 package zzl.utils; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 9 import android.os.Environment; 10 11 public class File_Utils { 12 private String SDPATH; 13 public File_Utils(){ 14 SDPATH = Environment.getExternalStorageDirectory()+"/"; 15 } 16 //得到當(dāng)前外部存儲(chǔ)設(shè)備的目錄 17 public String getSDPATH(){ 18 return SDPATH; 19 } 20 21 //在SD卡上創(chuàng)建文件: 22 public File createSDFile(String dirAndFilename) throws IOException{ 23 File file = new File(SDPATH+dirAndFilename); 24 file.createNewFile(); 25 return file; 26 } 27 28 //在SD卡上創(chuàng)建目錄 29 public File createSDDir(String dirName){ 30 File dir = new File(SDPATH+dirName); 31 dir.mkdirs(); 32 return dir; 33 } 34 //判斷SD卡上的文件夾是否存在 35 public boolean isFileExist(String fileName){ 36 File file = new File(SDPATH + fileName); 37 return file.exists(); 38 } 39 40 //將一個(gè)InputStream里面的數(shù)據(jù)寫到SD卡中 41 public File write2SDFromInputStream(String path,String fileName,InputStream in){ 42 File file = null; 43 OutputStream out = null; 44 try { 45 createSDDir(path); 46 try{file = createSDFile(path+fileName);} 47 catch(Exception e){ 48 System.out.println("createSDFile 失敗"); 49 } 50 51 out = new FileOutputStream(file); 52 byte buf[] = new byte[1024*5]; 53 int ch = 0; 54 while((ch = in.read(buf))!=-1){ 55 out.write(buf); 56 } 57 out.flush(); 58 59 } catch (IOException e) { 60 System.out.println("SD寫入失敗!"); 61 e.printStackTrace(); 62 }finally{ 63 if(out!=null) 64 try { 65 out.close(); 66 } catch (IOException e) { 67 e.printStackTrace(); 68 System.out.println("SD寫入流關(guān)閉失敗!"); 69 } 70 } 71 return file; 72 } 73 74 }總結(jié):
? ? 1、要達(dá)到連接網(wǎng)絡(luò)的效果,需要在download ?Manifest 中加入下面三句代碼:
? ? ? ? <uses-sdk android:minSdkVersion="4"/>
? ? ? ?<uses-permission android:name="android.permission.INTERNET"/>
? ? ? ?<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
? ? 2、因?yàn)椴皇钦嬲倪B接到網(wǎng)路,測試的時(shí)候需要在cmd中輸入adb ?shell 進(jìn)行驗(yàn)證,當(dāng)然這個(gè)的操作我們之前在SQlite那一節(jié)中介紹過了
? ? 3、總的整節(jié)視頻看下來,總覺得還是很多東西沒有消化的,很多mars老師自己寫的東西,很多函數(shù)的調(diào)用還有一些不是很了解的,還是需要再研究一下的。
? ? 4、點(diǎn)擊下載文本文件,效果如下:
? ? ? ??
? ? ? ?而下載Mp3文件則還是有一定的bug,還需要再調(diào)試調(diào)試。
總結(jié)
以上是生活随笔為你收集整理的Android 学习 笔记_05. 文件下载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jQuery DOM 节点操作
- 下一篇: xenserver6.2 内存leak故