Android文件的下载

转载自:http://blog.csdn.net/chichoxian/article/details/8566481


目录(?)[+]

1.主要内容

1.使用Http协议下载文件
2.将下载的文件写入SDCARD中

2.文件下载的主要步骤

创建一个HttpURLConnection对象
         HttpURLConnection  urlConn = (HttpURLConnection)url.openConnection();
url为一个URL的对象
获得一个inputStream 对象 
        urlConn.getInputStream()(输入流是指向程序当中读入数据)
网络访问的权限
    android.permission.INTERNET
这个需要在Manifest中进行注册

这里演示一个程序既能进行MP3的下载又能进行文本文件的下载,它由两个按钮组成,一个下载文本文件一个下载MP3文件

3.实际操作

类的结构示意图:



第一个按钮用来下载文本文件,第二个按钮用来下载Mp3文件
文件布局的源代码如下所示:
[html]  view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     tools:context=".MainActivity" >  
  7.   
  8.   <Button    
  9.     android:id="@+id/downloadTxt"  
  10.     android:layout_width="fill_parent"   
  11.     android:layout_height="wrap_content"   
  12.     android:text="下载文本文件"  
  13.     />  
  14. <Button    
  15.     android:id="@+id/downloadMp3"  
  16.     android:layout_width="fill_parent"   
  17.     android:layout_height="wrap_content"   
  18.     android:text="下载MP3文件 "  
  19.     />  
  20. </LinearLayout>  

在这里我们需要创建两个包一个包中含有一个类用于下载文件
另一个包名为Utils,这个是一个工具包其中包含两个类:一个为FileUtils,另一个为HttpDownLoader
下面来深入看看其的作用是:
这个时候我们来看看HttpDownLoader这个类:
我们在这个类中定义两个函数:download
在这个类中定义一个私有的属性:   private  URL url = null;
函数的形参为要下载内容的地址
[java]  view plain copy
  1. public String download(String urlStr){  
  2.         //在这里设置一个形参它用来保存下载的文本文件中的所有内容,它用于下载任何类型的文本文件  
  3.         StringBuffer sb = new StringBuffer();  
  4.         String line = null;  
  5.         BufferedReader buffer = null//使用它可以每次读取一行文件  
  6.         try{  
  7.             //创建一个URL的对象  
  8.             url = new URL(urlStr);  
  9.             //创建一个HTTP链接  
  10.             HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();  
  11.             buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));  
  12.             while((line =buffer.readLine())!= null){  
  13.                 sb.append(line);  
  14.             }  
  15.         }catch(Exception e){  
  16.             e.printStackTrace();  
  17.         }finally{  
  18.             try{  
  19.                 buffer.close();  
  20.             }catch(Exception e){  
  21.                 e.printStackTrace();  
  22.             }  
  23.         }  
  24.         return sb.toString();  
  25.     }  
在这里我们使用了BufferedReader可以每次读取一行

在这里我们使用

 

buffer = new BufferedReader(newInputStreamReader(urlConn.getInputStream()));

BufferedReader buffer = null;

 

这样我们可以每次都读取一行。sb对象中存储了有关的下载内容,最后作为返回值  使用HttpURLConnection 来建立连接

在这里使用了java的IO流,他使用了装饰着设计模式,urlConn存储的是网络上的资源的地址,我们通过getInputStream来建立了一条“管道”,把他所指的地址的内容导入到我们的程序中。

在这里,getInutStream的到的是字节流,这个时候通过inputStreamReader转换为字符流,再通过BuffererReader一步步的扩大。由于使用的是BufferReader所以可以一行行的读取。我们

使用了

         while((line =buffer.readLine())!= null){

                                     sb.append(line);

                            }

当读到文件的末尾的时候就结束.注意使用异常处理来读取。

这里使用了标准的java异常处理函数格式:

try{

....

}catch(Exception e){

...

}finally{

 //Do

}

注意:1.以上方法只适用于读取文本文件,读取MP3文件还需要重写方法。

2、android是基于权限的,所以要记得在AndroidManifest.xml注册。要得到当前设备SD卡的目录我们使用:Environment.getExternalStorageDirectory(),得到外部存储设备。注意不要把目录写死

访问SD卡的权限:android.permission.WRITE_EXTERNAL_STORAGE

 

之后我们来看另一个类:

[java]  view plain copy
  1. package grace.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.           // /SDCARD  
  19.            SDPATH = Environment.getExternalStorageState() + "/";  
  20.        }  
  21.          
  22.        /** 
  23.         * 在SD卡上创建目录 
  24.         */  
  25.        public File createSDDir(String dirName){  
  26.            File dir = new File(SDPATH +dirName);  
  27.            dir.mkdir();  
  28.            return dir;  
  29.        }  
  30.          
  31.        /*** 
  32.         * 在SD卡上创建文件 
  33.         *  
  34.         * @throws IOException 
  35.         */  
  36.        public File createSDFile(String fileName) throws IOException{  
  37.              File file = new File(SDPATH +fileName);  
  38.              file.createNewFile();  
  39.              return file;   
  40.        }  
  41.          
  42.          
  43.        /** 
  44.         * 判断SD卡上的文件夹是否存在 
  45.         */  
  46.        public boolean isFileExist(String fileName){  
  47.            File file = new File(SDPATH +fileName);  
  48.            return file.exists();  
  49.        }  
  50.          
  51.        /** 
  52.         * 将一个InputStream里面的数据写入到SD卡中 
  53.         */  
  54.        public File write2SDFromInput(String path, String fileName, InputStream input){  
  55.            File file = null;  
  56.            OutputStream output = null;  
  57.            try{  
  58.                createSDDir(path);  
  59.                file = createSDFile(path + fileName);  
  60.                output = new FileOutputStream(file);  
  61.                byte buffer[] = new byte4*1024];  
  62.                while((input.read(buffer))!=-1){  
  63.                    output.write(buffer);  
  64.                }  
  65.                output.flush();  
  66.            }  
  67.            catch(Exception e){  
  68.                e.printStackTrace();  
  69.            }  
  70.            finally{  
  71.                try{  
  72.                    output.close();  
  73.                }catch(Exception e){  
  74.                    e.printStackTrace();    
  75.                }  
  76.            }  
  77.              
  78.            return file;  
  79.        }  
  80. }  

现在我们在创建一个方法,使inputStream里的数据写入到SDCARD中我们制定的地方。这是我们创建方法:

 public File write2SDFromInput(String path,String fileName, InputStream input)

这个函数的第一个形参指的就是我们指定的存储路径,第二个参数指的就是文件名,inputStream实质上就是我们在HttpDownloader类当中所保存的数据。现在我们要把它写进sdcard当中。

我们创建一个file对象调用我们刚才写的方法,在创建一个outPutStream对象。

 createSDDir(path);

 file= createSDFile(path + fileName);

这里我们先创建一个目录再把文件保存在所指的目录当中。

[java]  view plain copy
  1. output = new FileOutputStream(file);  
  2.            byte buffer[] = new byte4*1024];  
  3.            while((input.read(buffer))!=-1){  
  4.                output.write(buffer);  
  5.            }  
  6.            output.flush();  

这里我们创建一个输出流让它对准文件,向其中写入我们要写的数据。

这里用到了一个过渡,那就是buffer,先从输入流中读入数据到一个缓冲区,在冲缓冲区中把数据读出写入到文件当中去。

要记得清空缓冲流,判断是不是有异常。

之后我们再来看HttpDownloader这个类当中的另一个方法:

[java]  view plain copy
  1.         /** 
  2.  * 下载任意形式的文件 
  3.  */  
  4. //第一个参数是想要下载的文件参数地址,第二个为存放的位置,第三个为你自己取的文件名  
  5. public int downFile(String urlStr, String path,String fileName){  
  6.     InputStream inputStream = null;  
  7.     try{  
  8.         FileUtils fileUtils = new FileUtils();  
  9.           
  10.         if(fileUtils.isFileExist(path +fileName)){  
  11.             return 1 ;  
  12.         }  
  13.         else{  
  14.             inputStream = getInputStreamFromUrl(urlStr);  
  15.             File  resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);  
  16.             if(resultFile == null){  
  17.                 return -1;  
  18.             }  
  19.         }  
  20.     }catch(Exception e){  
  21.         e.printStackTrace();  
  22.         return -1;  
  23.     }finally{  
  24.         try{  
  25.             inputStream.close();  
  26.         }catch(Exception e){  
  27.             e.printStackTrace();  
  28.         }  
  29.           
  30.     }  
  31.     return 0;  
  32.       
  33. }  

这个函数我们用它来读取MP3格式的文件。这个方法的返回值是整形。该函数返回整形 -1:代表下载文件出错 ,0:代表下载文件成功 ,1:代表文件已经存在。

第一个参数是想要下载的文件参数地址也就是下载的网址,第二个为存放的位置,第三个为你自己取的文件名

         publicint downFile(String urlStr, String path,String fileName)

我们用刚才写好的类来判断要下载的文件是否已经存在。

   

[java]  view plain copy
  1. FileUtils fileUtils = new FileUtils();  
  2.                             
  3.                            if(fileUtils.isFileExist(path+fileName)){  
  4.                                     return1 ;  
  5.                            }  

如果存在返回1.

inputStream =getInputStreamFromUrl(urlStr);

File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);

要是文件不存在我们就调用getInoutStreamFromUrl方法获得想要下载的文件的网址。

[java]  view plain copy
  1. private InputStream getInputStreamFromUrl(String urlStr)  
  2.             throws MalformedURLException,IOException {  
  3.         // TODO Auto-generated method stub  
  4.         url = new URL(urlStr);  
  5.         HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();  
  6.         InputStream inputStream =urlConn.getInputStream();  
  7.         return inputStream;  
  8.     }  
  9. }  

这个函数是我们自己写的,和刚才download函数很像。

这个时候我们来看一下HttpDownloader类的全貌:
[java]  view plain copy
  1. package grace.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. public class HttpDownloader {  
  13.     private URL url = null;  
  14.       
  15.     /*** 
  16.      * 根据URL下载文件 
  17.      *  @param 
  18.      *  @return 
  19.      */  
  20.     public String download(String urlStr){  
  21.         //在这里设置一个形参它用来保存下载的文本文件中的所有内容,它用于下载任何类型的文本文件  
  22.         StringBuffer sb = new StringBuffer();  
  23.         String line = null;  
  24.         BufferedReader buffer = null//使用它可以每次读取一行文件  
  25.         try{  
  26.             //创建一个URL的对象  
  27.             url = new URL(urlStr);  
  28.             //创建一个HTTP链接  
  29.             HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();  
  30.             buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));  
  31.             while((line =buffer.readLine())!= null){  
  32.                 sb.append(line);  
  33.             }  
  34.         }catch(Exception e){  
  35.             e.printStackTrace();  
  36.         }finally{  
  37.             try{  
  38.                 buffer.close();  
  39.             }catch(Exception e){  
  40.                 e.printStackTrace();  
  41.             }  
  42.         }  
  43.         return sb.toString();  
  44.     }  
  45.     /** 
  46.      * 下载任意形式的文件 
  47.      */  
  48.     //第一个参数是想要下载的文件参数地址,第二个为存放的位置,第三个为你自己取的文件名  
  49.     public int downFile(String urlStr, String path,String fileName){  
  50.         InputStream inputStream = null;  
  51.         try{  
  52.             FileUtils fileUtils = new FileUtils();  
  53.               
  54.             if(fileUtils.isFileExist(path +fileName)){  
  55.                 return 1 ;  
  56.             }  
  57.             else{  
  58.                 inputStream = getInputStreamFromUrl(urlStr);  
  59.                 File  resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);  
  60.                 if(resultFile == null){  
  61.                     return -1;  
  62.                 }  
  63.             }  
  64.         }catch(Exception e){  
  65.             e.printStackTrace();  
  66.             return -1;  
  67.         }finally{  
  68.             try{  
  69.                 inputStream.close();  
  70.             }catch(Exception e){  
  71.                 e.printStackTrace();  
  72.             }  
  73.               
  74.         }  
  75.         return 0;  
  76.           
  77.     }  
  78.     private InputStream getInputStreamFromUrl(String urlStr)  
  79.             throws MalformedURLException,IOException {  
  80.         // TODO Auto-generated method stub  
  81.         url = new URL(urlStr);  
  82.         HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();  
  83.         InputStream inputStream =urlConn.getInputStream();  
  84.         return inputStream;  
  85.     }  
  86.       
  87.   
  88. }  

下面我们来看一下DownLoad这个类的实现情况:

[java]  view plain copy
  1. package com.example.download01;  
  2.   
  3.   
  4. import grace.utils.HttpDownloader;  
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.view.Menu;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11.   
  12.   
  13. public class Download extends Activity {  
  14.       
  15.     private Button downloadTxtButton;  
  16.     private Button downloadMp3Button;  
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.         downloadTxtButton = (Button)findViewById(R.id.downloadTxt);  
  22.         downloadMp3Button = (Button)findViewById(R.id.downloadMp3);  
  23.         downloadTxtButton.setOnClickListener(new DownloadTxtListener());  
  24.         downloadMp3Button.setOnClickListener(new DownloadMp3Listener());  
  25.     }  
  26.     class DownloadTxtListener implements OnClickListener{  
  27.   
  28.   
  29.         @Override  
  30.         public void onClick(View v) {  
  31.             // TODO Auto-generated method stub  
  32.             HttpDownloader httpDownloader = new HttpDownloader();  
  33.             String lrc = httpDownloader.download("http://192.168.1.107:8080/voa1500/a1.lrc");  
  34.             System.out.println(lrc);  
  35.         }  
  36.           
  37.     }  
  38.       
  39.     class DownloadMp3Listener implements OnClickListener{  
  40.   
  41.   
  42.         @Override  
  43.         public void onClick(View v) {  
  44.             // TODO Auto-generated method stub  
  45.             HttpDownloader httpDownloader = new HttpDownloader();  
  46.             int result = httpDownloader.downFile("http://192.168.1.107:8080/voa1500/a1.mp3""voa/""a1.mp3");  
  47.             System.out.println(result);  
  48.               
  49.         }  
  50.           
  51.     }  
  52.     @Override  
  53.     public boolean onCreateOptionsMenu(Menu menu) {  
  54.         // Inflate the menu; this adds items to the action bar if it is present.  
  55.         getMenuInflater().inflate(R.menu.main, menu);  
  56.         return true;  
  57.     }  
  58.   
  59.   
  60. }  

这样整个下载功能就已经实现了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值