使用Http協議下載檔案,寫入SD卡中
下載步驟:
1、建立一個HttpURLConnection對象
HttpURLConnection urlConn =
(HttpURLConnection )url.openConnection();
2、獲得一個InputStream對象
urlConn.getInoutStream()
3、設定網路存取權限(manifest檔案中設定)
android.permission.INTERNET
訪問SD卡:
1. 得到SD卡的目錄
Environment.getExternalStorageDirectory()
2. 訪問SD卡的許可權:
android.permission.WRITE_EXTERNAL_STORAGE
注意:一定不要忘記設定許可權
Manifest.xml檔案:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="mars.download" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="4" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".DownloadActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <!-- 設定網路下載許可權和SD卡寫入許可權 --> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/></manifest>
DownloadActivity.java:
package mars.download;import mars.utils.HttpDownloader;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class DownloadActivity extends Activity { /** Called when the activity is first created. */private Button downloadTxtButton;private Button downloadMp3Button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); downloadTxtButton = (Button)findViewById(R.id.downloadTxt); downloadMp3Button = (Button)findViewById(R.id.downloadMp3); downloadTxtButton.setOnClickListener(new DownLoadTxtListener()); downloadMp3Button.setOnClickListener(new DownLoadMp3Listener()); }class DownLoadTxtListener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubHttpDownloader httpDownloader = new HttpDownloader();String str = httpDownloader.download("http://ishare.sina.cn/download.php?action=loading&id=13912266&cid=05_14&p=1");System.out.println("Download");System.out.println(str);}}class DownLoadMp3Listener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString urlStr = "http://ishare.sina.cn/download.php?action=loading&id=13912266&cid=05_14&p=1";HttpDownloader httpDownloader = new HttpDownloader();int state = httpDownloader.downFile(urlStr, "voa/", "myFile");System.out.println(state);}}}
HttpDownloader.java:
package mars.utils;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class HttpDownloader {private URL url = null;/** * 根據URL下載檔案 * 1. 建立一個URL對象 * 2. 通過URL對象,建立一個HttpURLConnection對象 * 3. 得到InputStream * 4. 從InputStream當中讀取資料 *///文字檔的下載public String download(String urlStr){StringBuffer sb = new StringBuffer();String line = null;BufferedReader buffer = null;try{//建立一個URL對象url = new URL(urlStr);//建立一個Http串連HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();//使用IO流讀取資料/** * urlConn.getInputStream()得到的是位元組流 * 套一層InputStreamReader得到的是字元流 * 在套一層BufferedReader得到的字元流就可以使用readLine按行讀取資料了 */buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));while((line = buffer.readLine())!=null){sb.append(line);}}catch(Exception e){System.out.println("Error");e.printStackTrace();}finally{try{buffer.close();}catch(Exception e){e.printStackTrace();}}return sb.toString();}//下載檔案並寫入到SD卡中//參數:url地址,檔案儲存體目錄絕對路徑,儲存的檔案名稱public int downFile(String urlStr,String path,String fileName){InputStream inputStream = null;try{FileUtils fileUtils = new FileUtils();//如果檔案已經存在則返回1if(fileUtils.isFileExist(path+fileName)){return 1;}else{//根據url地址得到檔案輸入資料流inputStream = getInputStreamFromUrl(urlStr);//將輸入資料流寫入SD卡,具體過程見FileUtils.javaFile resultFile = fileUtils.writeSDFromInput(path, fileName, inputStream);if(resultFile == null){return -1;}}} catch(Exception e){e.printStackTrace();return -1;} finally{try{inputStream.close();} catch(Exception e){e.printStackTrace();}}return 0;}//根據URL地址得到檔案輸入資料流public InputStream getInputStreamFromUrl(String urlStr)throws MalformedURLException, IOException{url = new URL(urlStr);HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();InputStream inputStream = urlConn.getInputStream();return inputStream;}}
FileUtils.java:
package mars.utils;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import android.os.Environment;/** * 此類是操作SD卡檔案的封裝 * 包括判斷檔案(夾)是否存在,建立檔案(夾),將檔案流寫入檔案 * * @author Administrator * */public class FileUtils {//SD卡的路徑名private String SDPATH;public String getSDPATH(){return SDPATH;}public FileUtils(){//得到當前外部存放裝置的目錄SDPATH = Environment.getExternalStorageDirectory()+"/";}/** * 在SD卡上建立檔案 * */public File createSDFile(String fileName)throws IOException{//根據檔案的全路徑名得到檔案對象File file = new File(SDPATH + fileName);//建立檔案file.createNewFile();return file;}/** * 在SD卡上建立目錄 */public File createSDDir(String dirName){File dir = new File(SDPATH + dirName);dir.mkdir();return dir;}/** * 判斷檔案夾是否存在 */public boolean isFileExist(String fileName){File file = new File(SDPATH + fileName);return file.exists();}/** * 將一個InputStream裡面的資料寫入到SD卡中 *///參數:檔案存放路徑(絕對目錄路徑),檔案名稱,輸入資料流public File writeSDFromInput(String path,String fileName,InputStream input){File file = null;OutputStream output = null;try{//建立檔案儲存體目錄createSDDir(path);//建立檔案file = createSDFile(path+fileName);//擷取建立檔案的輸出資料流output = new FileOutputStream(file);//緩衝區byte buffer [] = new byte[4 * 1024];//從輸入資料流中依次讀入資料並輸出到檔案中,每次4個位元組while((input.read(buffer))!= -1){output.write(buffer);}//清空緩衝output.flush();}catch(Exception e){e.printStackTrace();}finally{try{//關閉輸出資料流output.close();}catch(Exception e){e.printStackTrace();}}return file;}}