Android之文件下載

fmms 12年前發布 | 41K 次閱讀 Android Android開發 移動開發

在手機上下載一些文件是很常見的,比如下載一本書,下載一首Mp3等等,下面就來通過一個實例來簡單介紹一下文件的下載。

文件下載實現的基本步驟:創建一個HttpURLConnection對象,獲得一個InputStream對象,設置網絡訪問權限。

在這個實例中實現歌詞和歌曲MP3的下載。

首先我們先看一下布局文件,很簡單,只有兩個Button控件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="

<Button 
    android:id="@+id/downloadText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="downloadText"/>
<Button 
    android:id="@+id/downloadMp3"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="downloadMp3"/>

</LinearLayout></pre>

下載文件需要用到兩個utils工具類,一個工具類(HttpDownloader.java)是用來下載文件用的,另一個(FileUtils.java)是用來將下載的文件寫入到SD卡中: /Download/src/cn/android/sword/utils/HttpDownloader.java
package cn.android.sword.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;

import android.util.Log;

public class HttpDownloader { private final static String SWORD="SWORD"; public String download(String urlStr){

    URL url = null;
    StringBuffer sb = new StringBuffer();
    String line = null;
    BufferedReader buffer = null;

    try {
        //創建一個URL對象
        url = new URL(urlStr);

        //創建一個Http連接
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

        //使用IO流讀取數據
        buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        while((line=buffer.readLine())!=null){
            sb.append(line);
        }

    }catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            buffer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
//返回-1下載文件失敗,返回0下載成功,返回1則是文件已存在
public int downFile(String urlStr,String path,String fileName){
    InputStream inputStream = null;

    FileUtils fileUtils = new FileUtils();
    if(fileUtils.isFileExist(fileName)){
        return 1;
    }else{
        try {
            inputStream = getInputSteamFromUrl(urlStr);
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
        if(resultFile == null){
            return -1;
        }
    }
    try {
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 0;
}

private InputStream getInputSteamFromUrl(String urlStr) throws MalformedURLException, IOException {
    URL url = null;
    url = new URL(urlStr);
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    InputStream inputStream = urlConn.getInputStream();
    return inputStream;
}

}</pre>/Download/src/cn/android/sword/utils/FileUtils.java

package cn.android.sword.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;

public class FileUtils { private String SDPATH;

public String getSDPATH(){
    return SDPATH;
}
public FileUtils(){
    //得到當前外部存儲設備的目錄
    // /SDCARD
    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;
}

/*
 * 判斷SD卡上的文件夾是否存在
 */
public boolean isFileExist(String fileName){
    File file = new File(SDPATH+fileName);
    return file.exists();
}

/*
 * 將一個InputStream里面的數據寫入到SD卡中
 */

public File write2SDFromInput(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];
        //寫入數據
        while((input.read(buffer))!=-1){
            output.write(buffer);
        }
        //清空緩存
        output.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            //關閉輸出流
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file;
}

}</pre>在Activity中:
/Download/src/cn/android/sword/download/DownloadActivity.java

package cn.android.sword.download;

import cn.android.sword.utils.HttpDownloader; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;

/*
 文件下載的步驟:
1:創建一個Ht't'p'URLConnection對象:HttpURLConnection urlConn = (HttpURLConnection)url.o'penConnection;
2:獲得一個InputStream對象:urlConn.getInputStream();
3:設置網絡訪問權限:android.permissior.INTERNET;

訪問SD卡步驟:
得到當前設備SD卡的目錄;
Environment.getExternalStorageDirectory();
訪問SD卡的權限:
android:permission.WRITE_EXTERNAL_STORAGE
 */

public class DownloadActivity extends Activity implements OnClickListener{ private final static String SWORD="SWORD"; //聲明兩個按鈕控件 Button downloadText; Button downloadMp3; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViews(); } //根據Id得到控件 private void findViews() { downloadText = (Button) this.findViewById(R.id.downloadText); downloadMp3 = (Button) this.findViewById(R.id.downloadMp3); //添加監聽事件 downloadText.setOnClickListener(this); downloadMp3.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.downloadText: HttpDownloader httpDownloader = new HttpDownloader(); //所要下載文件的url路徑 String lrc = httpDownloader.download("Android之文件下載

點擊downloadText,查看控制臺日志輸出:Android之文件下載

可以看到亂碼的文件內容,然后點擊downloadMp3,在SD卡的dir目錄下我們能看到一個new.mp3的文件,這說明我們的文件下載成功了。

轉自:
http://blog.csdn.net/jjaze3344/article/details/7251527

 本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!