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文件
文件布局的源代码如下所示:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity" >
-
- <Button
- android:id="@+id/downloadTxt"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下载文本文件"
- />
- <Button
- android:id="@+id/downloadMp3"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下载MP3文件 "
- />
- </LinearLayout>
在这里我们需要创建两个包一个包中含有一个类用于下载文件
另一个包名为Utils,这个是一个工具包其中包含两个类:一个为FileUtils,另一个为HttpDownLoader
下面来深入看看其的作用是:
这个时候我们来看看HttpDownLoader这个类:
我们在这个类中定义两个函数:download
在这个类中定义一个私有的属性: private URL url = null;
函数的形参为要下载内容的地址
- public String download(String urlStr){
-
- StringBuffer sb = new StringBuffer();
- String line = null;
- BufferedReader buffer = null;
- try{
-
- url = new URL(urlStr);
-
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
- while((line =buffer.readLine())!= null){
- sb.append(line);
- }
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- try{
- buffer.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- return sb.toString();
- }
在这里我们使用了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
之后我们来看另一个类:
- package grace.utils;
-
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
-
- import android.os.Environment;
-
- public class FileUtils {
- private String SDPATH;
-
- public String getSDPATH(){
- return SDPATH;
- }
- public FileUtils(){
-
- SDPATH = Environment.getExternalStorageState() + "/";
- }
-
-
-
-
- public File createSDDir(String dirName){
- File dir = new File(SDPATH +dirName);
- dir.mkdir();
- return dir;
- }
-
-
-
-
-
-
- public File createSDFile(String fileName) throws IOException{
- File file = new File(SDPATH +fileName);
- file.createNewFile();
- return file;
- }
-
-
-
-
-
- public boolean isFileExist(String fileName){
- File file = new File(SDPATH +fileName);
- return file.exists();
- }
-
-
-
-
- public File write2SDFromInput(String path, String fileName, InputStream input){
- File file = null;
- OutputStream output = null;
- try{
- createSDDir(path);
- file = createSDFile(path + fileName);
- output = new FileOutputStream(file);
- byte buffer[] = new byte[ 4*1024];
- while((input.read(buffer))!=-1){
- output.write(buffer);
- }
- output.flush();
- }
- catch(Exception e){
- e.printStackTrace();
- }
- finally{
- try{
- output.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
-
- return file;
- }
- }
现在我们在创建一个方法,使inputStream里的数据写入到SDCARD中我们制定的地方。这是我们创建方法:
public File write2SDFromInput(String path,String fileName, InputStream input)
这个函数的第一个形参指的就是我们指定的存储路径,第二个参数指的就是文件名,inputStream实质上就是我们在HttpDownloader类当中所保存的数据。现在我们要把它写进sdcard当中。
我们创建一个file对象调用我们刚才写的方法,在创建一个outPutStream对象。
createSDDir(path);
file= createSDFile(path + fileName);
这里我们先创建一个目录再把文件保存在所指的目录当中。
- output = new FileOutputStream(file);
- byte buffer[] = new byte[ 4*1024];
- while((input.read(buffer))!=-1){
- output.write(buffer);
- }
- output.flush();
这里我们创建一个输出流让它对准文件,向其中写入我们要写的数据。
这里用到了一个过渡,那就是buffer,先从输入流中读入数据到一个缓冲区,在冲缓冲区中把数据读出写入到文件当中去。
要记得清空缓冲流,判断是不是有异常。
之后我们再来看HttpDownloader这个类当中的另一个方法:
-
-
-
-
- public int downFile(String urlStr, String path,String fileName){
- InputStream inputStream = null;
- try{
- FileUtils fileUtils = new FileUtils();
-
- if(fileUtils.isFileExist(path +fileName)){
- return 1 ;
- }
- else{
- inputStream = getInputStreamFromUrl(urlStr);
- File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
- if(resultFile == null){
- return -1;
- }
- }
- }catch(Exception e){
- e.printStackTrace();
- return -1;
- }finally{
- try{
- inputStream.close();
- }catch(Exception e){
- e.printStackTrace();
- }
-
- }
- return 0;
-
- }
这个函数我们用它来读取MP3格式的文件。这个方法的返回值是整形。该函数返回整形 -1:代表下载文件出错 ,0:代表下载文件成功 ,1:代表文件已经存在。
第一个参数是想要下载的文件参数地址也就是下载的网址,第二个为存放的位置,第三个为你自己取的文件名
publicint downFile(String urlStr, String path,String fileName)
我们用刚才写好的类来判断要下载的文件是否已经存在。
- FileUtils fileUtils = new FileUtils();
-
- if(fileUtils.isFileExist(path+fileName)){
- return1 ;
- }
如果存在返回1.
inputStream =getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
要是文件不存在我们就调用getInoutStreamFromUrl方法获得想要下载的文件的网址。
- private InputStream getInputStreamFromUrl(String urlStr)
- throws MalformedURLException,IOException {
-
- url = new URL(urlStr);
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- InputStream inputStream =urlConn.getInputStream();
- return inputStream;
- }
- }
这个函数是我们自己写的,和刚才download函数很像。
这个时候我们来看一下HttpDownloader类的全貌: