Android之文件下载

在手机上下载一些文件是很常见的,比如下载一本书,下载一首Mp3等等,下面就来通过一个实例来简单介绍一下文件的下载。

文件下载实现的基本步骤:创建一个HttpURLConnection对象,获得一个InputStream对象,设置网络访问权限。

在这个实例中实现歌词和歌曲MP3的下载。

首先我们先看一下布局文件,很简单,只有两个Button控件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <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>

下载文件需要用到两个utils工具类,一个工具类(HttpDownloader.java)是用来下载文件用的,另一个(FileUtils.java)是用来将下载的文件写入到SD卡中:

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;
    }
}

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;
    }
    
}

在Activity中:

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("http://192.168.1.101:8080/20111021/a.lrc");
            //日志打印输出
            Log.i(SWORD,""+lrc);
            break;
        case R.id.downloadMp3:
            HttpDownloader httpDownloader1 = new HttpDownloader();
            int result = httpDownloader1.downFile("http://192.168.1.101:8080/20111021/m.mp3","dir/","new.mp3");
            Log.i(SWORD,""+result);
            break;
        default:
            Log.i(SWORD,"ERROR");
            break;
        }
    }
}

本例子所下载的歌词文件和MP3文件均为我的pc上的tomcat中项目下的文件,所以需要启动我的tomcat service服务,在虚拟机上运行:

点击downloadText,查看控制台日志输出:

可以看到乱码的文件内容,然后点击downloadMp3,在SD卡的dir目录下我们能看到一个new.mp3的文件,这说明我们的文件下载成功了。

还有非常重要的一点,就是在清单中添加两个权限,一个访问SD卡的权限,还有互联网访问的权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

发表评论