zoukankan      html  css  js  c++  java
  • Android 学习 笔记_05. 文件下载

    文件下载的步骤:

      1、创建一个HttpURLConnection对象

                HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();

      2、获得一个InputStream()对象   

                urlConn.getInputStream();

      3、访问网路的权限

               android.permission.INTERNET

       现做一个小程序如下,能够下载文本文件和Mp3文件

                           

     main.xml

     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=".Download_Activity" >
     7 
     8     <Button 
     9         android:layout_width="fill_parent"
    10         android:layout_height="wrap_content"
    11         android:id="@+id/downloadText"
    12         android:text="@string/downloadTextButton"/>
    13     <Button 
    14         android:layout_width="fill_parent"
    15         android:layout_height="wrap_content"
    16         android:id="@+id/downloadMp3"
    17         android:text="@string/downloadMp3Button"/>
    18 </LinearLayout>

    Download_Activity.java

     1 package zzl.download;
     2 
     3 import zzl.utils.HttpDownload;
     4 import android.app.Activity;
     5 import android.os.Bundle;
     6 import android.view.View;
     7 import android.view.View.OnClickListener;
     8 import android.widget.Button;
     9 
    10 public class Download_Activity extends Activity {
    11 
    12     private Button downloadMp3Button;
    13     private Button downloadTextButton;
    14     @Override
    15     public void onCreate(Bundle savedInstanceState) {
    16         super.onCreate(savedInstanceState);
    17         setContentView(R.layout.main);
    18         downloadMp3Button=(Button)findViewById(R.id.downloadMp3);
    19         downloadTextButton=(Button)findViewById(R.id.downloadText);
    20         downloadMp3Button.setOnClickListener(new DownloadMp3Listener());
    21         downloadTextButton.setOnClickListener(new DownloadTextListener());
    22     }
    23     class DownloadTextListener implements OnClickListener{
    24 
    25         @Override
    26         public void onClick(View v) {
    27             // TODO Auto-generated method stub
    28             HttpDownload httpDownloader=new HttpDownload();
    29             String lrc =httpDownloader.download("http://photo.weibo.com/152611965/wbphotos/large/photo_id/3549709337146075?refer=weibofeedv5");
    30             System.out.println(lrc);
    31         }
    32     }
    33     class DownloadMp3Listener implements OnClickListener{
    34 
    35         @Override
    36         public void onClick(View v) {
    37             // TODO Auto-generated method stub
    38             HttpDownload httpDownloader=new HttpDownload();
    39             int result =httpDownloader.downloadFile("http://photo.weibo.com/152611965/wbphotos/large/photo_id/3549709337146075?refer=weibofeedv5","photo_id/","3549709337146075?refer=weibofeedv5");
    40             System.out.println(result);
    41         }
    42     }
    43 
    44 }

    HttpDownload.java

     1 package zzl.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.URL;
    10 
    11 
    12 /*前提:首先判断所下载的文件是否为纯文本文件
    13  * 1.创建一个URL对象
    14  * 2.通过URL对象获取HttpOpenConnection对象(代表和网络上的http对象的连接)
    15  * 3.获取InputStream对象
    16  * 4.读取数据
    17  * 5.将读取的数据写入SD卡
    18  * */
    19 public class HttpDownload {
    20     private URL url = null;
    21     
    22     //下载任何形式 的文本文件    
    23     public String download(String urlStr){
    24         StringBuffer sb = new StringBuffer();
    25         String line = null;
    26         BufferedReader bufr = null;
    27         
    28         try {                                                                        
    29             // 创建一个URL对象:调用URL函数,将地址传入
    30             url = new URL(urlStr);
    31             //通过URL创建一个HTTP连接                                                                 
    32              HttpURLConnection con =  (HttpURLConnection)url.openConnection();
    33             //使用IO流读取数据,这里使用到了转换流,提高读取效率  【【 字节流转换成字符流再转换成读取行数据】】
    34             bufr = new BufferedReader(new InputStreamReader(con.getInputStream()));
    35             while((line = bufr.readLine())!=null){
    36                 sb.append(line);
    37             }
    38             
    39         } catch (Exception e) {
    40             System.out.println("文本文件下载失败!");
    41             e.printStackTrace();
    42         }finally{
    43             if(bufr!=null)
    44                 try {
    45                     bufr.close();
    46                 } catch (IOException e) {
    47                     System.out.println("文本文件读取流关闭失败!");
    48                     e.printStackTrace();
    49                 }
    50         }
    51         return sb.toString();
    52         
    53     }
    54     //访问SD卡
    55     /* 1.得到当前设备SD卡的目录
    56      *     Environment.getExternalStorageDirectory()
    57      * */
    58     //可下载各种文件
    59     //返回 -1:代表下载文件出错        返回0:代表下载文件成功             返回 1:代表文件已经存在
    60     //fileName代表你将要存入SD卡中的文件名,可以定义自己的文件名
    61     public int downloadFile(String url,String path,String fileName){
    62         InputStream in = null;
    63         try {
    64             File_Utils utils = new File_Utils() ;
    65             //如果存在该文件了则返回1
    66             if(utils.isFileExist(path+fileName)){
    67                 return 1;
    68             }else{//否则则就获得否则则就通过调用File_Utils.java的write2SDFromInputStream函数写入SD卡中
    69                 in = getInputStreamFromUrl(url);
    70                 File resultFile = utils.write2SDFromInputStream(path, fileName, in);
    71                 if(resultFile == null){
    72                     return -1;
    73                 }
    74             }
    75             
    76         } catch (IOException e) {
    77             e.printStackTrace();
    78             return -1;
    79         }finally{
    80             if(in!=null){
    81             try {
    82                 in.close();
    83             } catch (IOException e) {
    84                 System.out.println("字节读取流关闭失败!");
    85                 e.printStackTrace();
    86               }
    87             }
    88         }
    89         return 0;
    90     }
    91     
    92     //将根据URL获取InputStream的功能封装起来,以便复用
    93     public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
    94             url = new URL(urlStr);
    95             HttpURLConnection con =  (HttpURLConnection) url.openConnection();
    96             InputStream in = con.getInputStream();
    97             return in;
    98     }
    99 }

    File_Utils.java

     1 package zzl.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 File_Utils {
    12     private String SDPATH; 
    13     public File_Utils(){
    14         SDPATH = Environment.getExternalStorageDirectory()+"/";
    15     }
    16     //得到当前外部存储设备的目录
    17     public String getSDPATH(){
    18         return SDPATH;
    19     }
    20     
    21     //在SD卡上创建文件:
    22     public File createSDFile(String dirAndFilename) throws IOException{
    23         File file = new File(SDPATH+dirAndFilename);
    24         file.createNewFile();
    25         return file;
    26     } 
    27     
    28     //在SD卡上创建目录
    29     public File createSDDir(String dirName){
    30         File dir = new File(SDPATH+dirName);
    31         dir.mkdirs();
    32         return dir;
    33     }
    34     //判断SD卡上的文件夹是否存在
    35     public boolean isFileExist(String fileName){
    36         File file = new File(SDPATH + fileName);
    37         return file.exists();
    38     }
    39 
    40     //将一个InputStream里面的数据写到SD卡中
    41     public File write2SDFromInputStream(String path,String fileName,InputStream in){
    42         File file = null;
    43         OutputStream out = null;
    44         try {
    45             createSDDir(path);
    46             try{file = createSDFile(path+fileName);}
    47             catch(Exception e){
    48                 System.out.println("createSDFile 失败");
    49             }
    50             
    51             out = new FileOutputStream(file);
    52             byte buf[] = new byte[1024*5];
    53             int ch = 0;
    54             while((ch = in.read(buf))!=-1){
    55                 out.write(buf);
    56             }
    57             out.flush();
    58         
    59         } catch (IOException e) {
    60             System.out.println("SD写入失败!");
    61             e.printStackTrace();
    62         }finally{
    63             if(out!=null)
    64                 try {
    65                     out.close();
    66                 } catch (IOException e) {
    67                     e.printStackTrace();
    68                     System.out.println("SD写入流关闭失败!");
    69                 }
    70         }
    71         return file;
    72     }
    73 
    74 }

    总结:

        1、要达到连接网络的效果,需要在download  Manifest 中加入下面三句代码:

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

        2、因为不是真正的连接到网路,测试的时候需要在cmd中输入adb  shell 进行验证,当然这个的操作我们之前在SQlite那一节中介绍过了

        3、总的整节视频看下来,总觉得还是很多东西没有消化的,很多mars老师自己写的东西,很多函数的调用还有一些不是很了解的,还是需要再研究一下的。

        4、点击下载文本文件,效果如下:

            

           而下载Mp3文件则还是有一定的bug,还需要再调试调试。

  • 相关阅读:
    【WPF】wpf image控件加载网络图片不显示问题,
    【VS】vs修改大小写快捷键
    【C#】菜单功能,将剪贴板JSON内容或者xml内容直接粘贴为类
    【异常】调用的目标发生了异常
    【MySQL】函数IFNULL、设置默认时间
    【Kindle】pdf转mobi适合kindle查看格式
    【WPF】中的文字修饰——上划线,中划线,基线与下划线
    vscode使用Eslint + prettier + beautify 格式化vue 代码不换行
    Office文件转PDF
    MSSQL同步刷新视图字段长度和源表保持一致
  • 原文地址:https://www.cnblogs.com/daomul/p/2913703.html
Copyright © 2011-2022 走看看