文件下载的步骤:

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     @Override15     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         @Override26         public void onClick(View v) {27             // TODO Auto-generated method stub28             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         @Override36         public void onClick(View v) {37             // TODO Auto-generated method stub38             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             //如果存在该文件了则返回166             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,还需要再调试调试。

更多相关文章

  1. 类和 Json对象
  2. NPM 和webpack 的基础使用
  3. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  4. 读取android手机流量信息
  5. android 使用html5作布局文件: webview跟javascript交互
  6. Android(安卓)多媒体扫描过程(Android(安卓)Media Scanner Proces
  7. android“设置”里的版本号
  8. Android开发环境搭建
  9. Android(安卓)Resource介绍和使用

随机推荐

  1. Android中的AIDL
  2. Android自动解除系统锁屏
  3. android进程间服务通信示例
  4. Android(安卓)Activity之间跳转与传值
  5. Android 实现记住用户名和密码的功能
  6. 在Linux下安装Android SDK
  7. adb logcat命令查看并过滤android输出log
  8. android 上下文菜单Context Menu--折腾一
  9. Unity调用高德地图API,获取定位信息(Androi
  10. cocos2d for android 项目的部署