Android之文件下载

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

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

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

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

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <Button   
  8.         android:id="@+id/downloadText"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="downloadText"/>  
  12.     <Button   
  13.         android:id="@+id/downloadMp3"  
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="downloadMp3"/>  
  17.       
  18. </LinearLayout>  

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

/Download/src/cn/android/sword/utils/HttpDownloader.java

  1. package cn.android.sword.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.MalformedURLException;  
  10. import java.net.URL;  
  11.   
  12. import android.util.Log;  
  13.   
  14. public class HttpDownloader {  
  15.     private final static String SWORD="SWORD";  
  16.     public String download(String urlStr){  
  17.   
  18.         URL url = null;  
  19.         StringBuffer sb = new StringBuffer();  
  20.         String line = null;  
  21.         BufferedReader buffer = null;  
  22.           
  23.         try {  
  24.             //创建一个URL对象  
  25.             url = new URL(urlStr);  
  26.               
  27.             //创建一个Http连接  
  28.             HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  29.               
  30.             //使用IO流读取数据  
  31.             buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));  
  32.               
  33.             while((line=buffer.readLine())!=null){  
  34.                 sb.append(line);  
  35.             }  
  36.               
  37.         }catch (Exception e) {  
  38.             e.printStackTrace();  
  39.         }finally{  
  40.             try {  
  41.                 buffer.close();  
  42.             } catch (IOException e) {  
  43.                 e.printStackTrace();  
  44.             }  
  45.         }  
  46.         return sb.toString();  
  47.     }  
  48.     //返回-1下载文件失败,返回0下载成功,返回1则是文件已存在  
  49.     public int downFile(String urlStr,String path,String fileName){  
  50.         InputStream inputStream = null;  
  51.           
  52.         FileUtils fileUtils = new FileUtils();  
  53.         if(fileUtils.isFileExist(fileName)){  
  54.             return 1;  
  55.         }else{  
  56.             try {  
  57.                 inputStream = getInputSteamFromUrl(urlStr);  
  58.             } catch (IOException e) {  
  59.                 e.printStackTrace();  
  60.                 return -1;  
  61.             }  
  62.             File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);  
  63.             if(resultFile == null){  
  64.                 return -1;  
  65.             }  
  66.         }  
  67.         try {  
  68.             inputStream.close();  
  69.         } catch (IOException e) {  
  70.             e.printStackTrace();  
  71.         }  
  72.         return 0;  
  73.     }  
  74.   
  75.     private InputStream getInputSteamFromUrl(String urlStr) throws MalformedURLException, IOException {  
  76.         URL url = null;  
  77.         url = new URL(urlStr);  
  78.         HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  79.         InputStream inputStream = urlConn.getInputStream();  
  80.         return inputStream;  
  81.     }  
  82. }  


/Download/src/cn/android/sword/utils/FileUtils.java

  1. package cn.android.sword.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 FileUtils {  
  12.     private String SDPATH;  
  13.       
  14.     public String getSDPATH(){  
  15.         return SDPATH;  
  16.     }  
  17.     public FileUtils(){  
  18.         //得到当前外部存储设备的目录  
  19.         // /SDCARD  
  20.         SDPATH = Environment.getExternalStorageDirectory()+"/";  
  21.     }  
  22.       
  23.     /*  
  24.      * 在SD卡上创建文件  
  25.      */  
  26.     public File createSDFile(String fileName) throws IOException{  
  27.         File file = new File(SDPATH+fileName);  
  28.         file.createNewFile();  
  29.         return file;  
  30.     }  
  31.       
  32.     /*  
  33.      * 在SD卡上创建目录  
  34.      */  
  35.       
  36.     public File createSDDir(String dirName){  
  37.         File dir = new File(SDPATH+dirName);  
  38.         dir.mkdir();  
  39.         return dir;  
  40.     }  
  41.       
  42.     /*  
  43.      * 判断SD卡上的文件夹是否存在  
  44.      */  
  45.     public boolean isFileExist(String fileName){  
  46.         File file = new File(SDPATH+fileName);  
  47.         return file.exists();  
  48.     }  
  49.       
  50.     /*  
  51.      * 将一个InputStream里面的数据写入到SD卡中  
  52.      */  
  53.       
  54.     public File write2SDFromInput(String path,String fileName,InputStream input){  
  55.         File file = null;  
  56.         OutputStream output = null;  
  57.         try {  
  58.             //创建目录  
  59.             createSDDir(path);  
  60.             //创建文件  
  61.             file = createSDFile(path+fileName);  
  62.             //创建输出流  
  63.             output = new FileOutputStream(file);  
  64.             //创建缓冲区  
  65.             byte buffer[] =  new byte[4*1024];  
  66.             //写入数据  
  67.             while((input.read(buffer))!=-1){  
  68.                 output.write(buffer);  
  69.             }  
  70.             //清空缓存  
  71.             output.flush();  
  72.         } catch (IOException e) {  
  73.             e.printStackTrace();  
  74.         }finally{  
  75.             try {  
  76.                 //关闭输出流  
  77.                 output.close();  
  78.             } catch (IOException e) {  
  79.                 e.printStackTrace();  
  80.             }  
  81.         }  
  82.         return file;  
  83.     }  
  84.       
  85. }  
在Activity中:
/Download/src/cn/android/sword/download/DownloadActivity.java
  1. package cn.android.sword.download;  
  2.   
  3. import cn.android.sword.utils.HttpDownloader;  
  4. import android.app.Activity;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.widget.Button;  
  10.   
  11.     /*  
  12.      文件下载的步骤:  
  13.     1:创建一个Ht't'p'URLConnection对象:HttpURLConnection urlConn = (HttpURLConnection)url.o'penConnection;  
  14.     2:获得一个InputStream对象:urlConn.getInputStream();  
  15.     3:设置网络访问权限:android.permissior.INTERNET;  
  16.       
  17.     访问SD卡步骤:  
  18.     得到当前设备SD卡的目录;  
  19.     Environment.getExternalStorageDirectory();  
  20.     访问SD卡的权限:  
  21.     android:permission.WRITE_EXTERNAL_STORAGE  
  22.      */  
  23.   
  24. public class DownloadActivity extends Activity implements OnClickListener{  
  25.     private final static String SWORD="SWORD";   
  26.     //声明两个按钮控件  
  27.     Button downloadText;  
  28.     Button downloadMp3;  
  29.     public void onCreate(Bundle savedInstanceState) {  
  30.         super.onCreate(savedInstanceState);  
  31.         setContentView(R.layout.main);  
  32.         findViews();  
  33.     }  
  34.     //根据Id得到控件  
  35.     private void findViews() {  
  36.         downloadText = (Button) this.findViewById(R.id.downloadText);  
  37.         downloadMp3 = (Button) this.findViewById(R.id.downloadMp3);  
  38.         //添加监听事件  
  39.         downloadText.setOnClickListener(this);  
  40.         downloadMp3.setOnClickListener(this);  
  41.     }  
  42.     @Override  
  43.     public void onClick(View v) {  
  44.         switch(v.getId()){  
  45.         case R.id.downloadText:  
  46.             HttpDownloader httpDownloader = new HttpDownloader();  
  47.             //所要下载文件的url路径  
  48.             String lrc = httpDownloader.download("http://192.168.1.101:8080/20111021/a.lrc");  
  49.             //日志打印输出  
  50.             Log.i(SWORD,""+lrc);  
  51.             break;  
  52.         case R.id.downloadMp3:  
  53.             HttpDownloader httpDownloader1 = new HttpDownloader();  
  54.             int result = httpDownloader1.downFile("http://192.168.1.101:8080/20111021/m.mp3","dir/","new.mp3");  
  55.             Log.i(SWORD,""+result);  
  56.             break;  
  57.         default:  
  58.             Log.i(SWORD,"ERROR");  
  59.             break;  
  60.         }  
  61.     }  
  62. }  

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


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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值