Android _文件下载

 Android 文件下载,在Android开发中很长用到,经常需要在应用程序中下载所需要的文件比如电子书,MP3格式的音乐文件,电影等。我在这里总结了一下,以后要用时可以直接拷贝,

代码分析:

  有两个工具类,HttpDownloader.java类中定义两个下载方法,download(String urlstr)下载纯文本文件,downfile(String urlStr,String path,String fileName)下载字节文件类。FileUtils.java类定义了写入sd卡的操作。Download.java类为主线程类,两个按钮,监听下载事件。

注意:

     在AndroidManifest.xml中添加网络访问权限

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

     在AndroidManifest.xml中加入访问SDCard的权限

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

代码:

   main.xml

[java]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"   
  10.     android:text="Android_hello word"  
  11.     />  
  12. <Button  
  13.     android:id="@+id/buttontxt"  
  14.     android:layout_width="300dp"  
  15.     android:layout_height="wrap_content"  
  16.     android:text="单击下载txt文件"  
  17.     />  
  18. <Button  
  19.     android:id="@+id/buttonmp3"  
  20.     android:layout_width="300dp"  
  21.     android:layout_height="wrap_content"  
  22.     android:text="单击下载mp3文件"  
  23.     />  
  24. </LinearLayout>  

  Download.java

[java]  view plain copy
  1. package com.example.download;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5.   
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9.   
  10. public class Download extends Activity {  
  11.     private Button buttontxt;  
  12.     private Button buttonmp3;  
  13.   
  14.     @Override  
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity_download);  
  18.         buttontxt = (Button) findViewById(R.id.buttontxt);  
  19.         buttontxt.setOnClickListener(new OnClickListener() {  
  20.   
  21.             public void onClick(View v) {  
  22.                 // TODO Auto-generated method stub  
  23.                 // TODO Auto-generated method stub  
  24.                 // 创建一个匿名线程用于下载文件  
  25.                 new Thread() {  
  26.                     public void run() {  
  27.                         HttpDownloader httpDownloader = new HttpDownloader();  
  28.                         // 调用httpDownloader对象的重载方法download下载txt文件  
  29.                         String txt = httpDownloader  
  30.                                 .download("http://www.baidu.com/");  
  31.                         System.out.println(txt);  
  32.                     }  
  33.                 }.start();  
  34.             }  
  35.   
  36.         });  
  37.   
  38.         buttonmp3 = (Button) findViewById(R.id.buttonmp3);  
  39.         // 为buttonmp3添加单击事件监听器  
  40.         buttonmp3.setOnClickListener(new OnClickListener() {  
  41.   
  42.             /* 
  43.              * (non-Javadoc) 
  44.              *  
  45.              * @see android.view.View.OnClickListener#onClick(android.view.View) 
  46.              */  
  47.             @Override  
  48.             public void onClick(View v) {  
  49.                 // TODO Auto-generated method stub  
  50.                 new Thread() {  
  51.                     public void run() {  
  52.                         try {  
  53.                             HttpDownloader httpDownloader = new HttpDownloader();  
  54.                             // 调用httpDownloader对象的重载方法download下载mp3文件  
  55.                             int result = httpDownloader  
  56.                                     .downfile(  
  57.                                             "http://sjrjy.apkzz.net/201011/291354164ea84578066309.jpg",  
  58.                                             "Android/""9.jpg");  
  59.                             System.out.println(result);  
  60.                         } catch (Exception e) {  
  61.                             e.printStackTrace();  
  62.                         }  
  63.                     }  
  64.                 }.start();  
  65.   
  66.             }  
  67.         });  
  68.     }  
  69.   
  70. }  

  HttpDownloader.java

[java]  view plain copy
  1. package com.example.download;  
  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. public class HttpDownloader {  
  13.   private URL url=null;  
  14.   public String download(String urlstr){  
  15.       StringBuffer stringBuffer=new StringBuffer();  
  16.       String line;  
  17.       BufferedReader bufferedReader=null;  
  18.       try {  
  19.         //创建一个URL对象  
  20.         url=new URL(urlstr);  
  21.         //得到一个HttpURLConnection对象  
  22.         HttpURLConnection httpsURLConnection=(HttpURLConnection) url.openConnection();  
  23.         // 得到IO流,使用IO流读取数据   
  24.         bufferedReader=new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));  
  25.         while((line=bufferedReader.readLine())!=null){//一行一行的读  
  26.             stringBuffer.append(line);  
  27.         }  
  28.               
  29.     } catch (Exception e) {  
  30.         e.printStackTrace();  
  31.     }   
  32.     return stringBuffer.toString();  
  33.         
  34.   }  
  35.   
  36.   // 该函数返回整形 -1:代表下载文件出错 ;0:代表下载文件成功; 1:代表文件已经存在   
  37.  public int downfile(String urlStr,String path,String fileName){  
  38.      InputStream inputstream=null;    
  39.      FileUtils fileUtils=new FileUtils();    
  40.      if(fileUtils.isExist(path+fileName))    
  41.          return 1;    
  42.      else    
  43.      {    
  44.          try {    
  45.              inputstream=getFromUrl(urlStr);    
  46.          } catch (IOException e) {    
  47.              e.printStackTrace();    
  48.          }    
  49.          File file=fileUtils.writeToSDPATHFromInput(path, fileName, inputstream);    
  50.          if(file!=null)    
  51.              return 0;    
  52.          else     
  53.              return -1;    
  54.      }    
  55.        
  56.        
  57.   
  58.        
  59.  }  
  60. //根据url字符串得到输入流    
  61. public InputStream getFromUrl(String urlStr) throws IOException    
  62. {           
  63.     url=new URL(urlStr);                
  64.     HttpURLConnection httpUrlConnection=(HttpURLConnection) url.openConnection();    
  65.     InputStream input=httpUrlConnection.getInputStream();       
  66.     return input;    
  67. }    
  68. }   

  FileUtils.java

[java]  view plain copy
  1. package com.example.download;  
  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 = null;  
  13.   
  14.     public String getSDPATH() {  
  15.         return SDPATH;  
  16.     }  
  17.   
  18.     public FileUtils() {  
  19.         // 获得当前外部存储设备SD卡的目录  
  20.         SDPATH = Environment.getExternalStorageDirectory() + "/";  
  21.     }  
  22.   
  23.     // 创建文件  
  24.     public File createFile(String fileName) throws IOException {  
  25.         File file = new File(SDPATH + fileName);  
  26.         file.createNewFile();  
  27.         return file;  
  28.     }  
  29.   
  30.     // 创建目录  
  31.     public File createDir(String fileName) throws IOException {  
  32.         File dir = new File(SDPATH + fileName);  
  33.         dir.mkdir();  
  34.         return dir;  
  35.     }  
  36.   
  37.     // 判断文件是否存在  
  38.     public boolean isExist(String fileName) {  
  39.         File file = new File(SDPATH + fileName);  
  40.         return file.exists();  
  41.     }  
  42.   
  43.     public File writeToSDPATHFromInput(String path, String fileName,  
  44.             InputStream inputstream) {  
  45.         File file = null;  
  46.         OutputStream outputstream = null;  
  47.         try {  
  48.             createDir(path);  
  49.             file = createFile(path + fileName);  
  50.             outputstream = new FileOutputStream(file);  
  51.             byte buffer[] = new byte[1024];  
  52.             // 将输入流中的内容先输入到buffer中缓存,然后用输出流写到文件中, /*真机测试,这段可能有问题  
  53.             /*while ((inputstream.read(buffer)) != -1) {  
  54.                 outputstream.write(buffer);  
  55.             }*/  
  56.             //用这段  
  57.             int length;  
  58.             while((length=(inputstream.read(buffer))) >0){  
  59.             outputstream.write(buffer,0,length);  
  60.             }  
  61.         } catch (Exception e) {  
  62.             e.printStackTrace();  
  63.         } finally {  
  64.             try {  
  65.                 inputstream.close();  
  66.                 outputstream.close();  
  67.             } catch (IOException e) {  
  68.                 e.printStackTrace();  
  69.             }  
  70.         }  
  71.         return file;  
  72.     }  
  73.   
  74. }  


[java]  view plain copy
  1.   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值