android_文件下载

转载自:http://blog.csdn.net/ycwol/article/details/44546337

android 在网络上下载文件

步骤 : 

1.使用HTTP协议下载文件

- 创建一个HttpURLConnection对象 : HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

- 获取一个InputStream对象 : urlConn.getInputStream()

- 访问网络的权限 : android.permission.INTERNET

2.将下载的文件写入SDCARD

- 得到当前设备SD卡的目录 : Environment.getExternalStrageDirectory()

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

代码 :  

activity_main.xml

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity" >  
  10.   
  11.     <Button  
  12.         android:id="@+id/btn_txt"  
  13.         android:layout_width="match_parent"  
  14.         android:layout_height="wrap_content"  
  15.         android:text="download lrc" />  
  16.       
  17.     <Button  
  18.         android:id="@+id/btn_mp3"  
  19.         android:layout_width="match_parent"  
  20.         android:layout_height="wrap_content"  
  21.         android:layout_below="@id/btn_txt"  
  22.         android:text="download mp3" />  
  23.   
  24. </RelativeLayout>  
MainActivity.java
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.chay.download;  
  2.   
  3. import com.chay.utils.HttpDownloader;  
  4.   
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.widget.Button;  
  10.   
  11. public class MainActivity extends Activity {  
  12.       
  13.     String urlStr_txt = "http://192.168.56.1:8080/mp3/wan.lrc";  
  14.     String urlStr_mp3 = "http://192.168.56.1:8080/mp3/wan.mp3";  
  15.     String path = "mp3/";  
  16.     String fileName = "wan.mp3";  
  17.     private Button downloadTxtButton;  
  18.     private Button downloadMp3Button;  
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_main);  
  24.         downloadTxtButton = (Button) findViewById(R.id.btn_txt);  
  25.         downloadTxtButton.setOnClickListener(new DownloadTxtListener());  
  26.         downloadMp3Button = (Button) findViewById(R.id.btn_mp3);  
  27.         downloadMp3Button.setOnClickListener(new DownloadMp3Listener());  
  28.     }  
  29.   
  30.     //下载歌词文件按钮监听器  
  31.     class DownloadTxtListener implements OnClickListener {  
  32.         @Override  
  33.         public void onClick(View v) {  
  34.             Thread t = new DownloadTxtThread();    
  35.             t.start();  
  36.             System.out.println("txt--->");  
  37.         }  
  38.     }  
  39.     //下载歌词文件线程  
  40.     class DownloadTxtThread extends Thread{  
  41.         @Override  
  42.         public void run() {  
  43.             HttpDownloader httpDownloader = new HttpDownloader();  
  44.             String lrc = httpDownloader.download(urlStr_txt);  
  45.             System.out.println(lrc);  
  46.         }  
  47.     }  
  48.     //下载MP3文件按钮监听器  
  49.     class DownloadMp3Listener implements OnClickListener {  
  50.         @Override  
  51.         public void onClick(View v) {  
  52.             Thread h = new DownMp3Thread();  
  53.             h.start();  
  54.             System.out.println("mp3--->");  
  55.         }  
  56.     }  
  57.     //下载MP3文件线程  
  58.     class DownMp3Thread extends Thread{  
  59.         @Override  
  60.         public void run() {  
  61.             HttpDownloader httpDownloader = new HttpDownloader();  
  62.             int result = httpDownloader.downFile(urlStr_mp3, path, fileName);  
  63.             System.out.println(result);  
  64.         }  
  65.     }     
  66. }  
工具类:
HttpDownloader.java
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.chay.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.      * 1.创建一个URL对象 
  18.      * 2.通过URL对象,创建一个HttpURLConnection对象 
  19.      * 3.得到InputStram 
  20.      * 4.从InputStream当中读取数据 
  21.      * @param urlStr 
  22.      * @return 
  23.      */  
  24.     public String download(String urlStr) {  
  25.         StringBuffer sb = new StringBuffer();  
  26.         String line = null;  
  27.         BufferedReader buffer = null;  
  28.         try {  
  29.             // 创建一个URL对象  
  30.             url = new URL(urlStr);  
  31.             // 创建一个Http连接  
  32.             HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  33.             // 使用IO流读取数据  
  34.             buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));  
  35.             while ((line = buffer.readLine()) != null) {  
  36.                 sb.append(line);  
  37.             }  
  38.         } catch (Exception e) {  
  39.             e.printStackTrace();  
  40.         } finally {  
  41.             try {  
  42.                 buffer.close();  
  43.             } catch (Exception e) {  
  44.                 e.printStackTrace();  
  45.             }  
  46.         }  
  47.         return sb.toString();  
  48.     }  
  49.   
  50.     /** 
  51.      * 该函数返回整形 -1:代表下载文件出错      0:代表下载文件成功      1:代表文件已经存在 
  52.      */  
  53.     public int downFile(String urlStr, String path, String fileName) {  
  54.         InputStream inputStream = null;  
  55.         try {  
  56.             FileUtils fileUtils = new FileUtils();  
  57.               
  58.             if (fileUtils.isFileExist(path + fileName)) {  
  59.                 return 1;  
  60.             } else {  
  61.                 inputStream = getInputStreamFromUrl(urlStr);  
  62.                 File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream);  
  63.                 if (resultFile == null) {  
  64.                     return -1;  
  65.                 }  
  66.             }  
  67.         } catch (Exception e) {  
  68.             e.printStackTrace();  
  69.             return -1;  
  70.         } finally {  
  71.             try {  
  72.                 inputStream.close();  
  73.             } catch (Exception e) {  
  74.                 e.printStackTrace();  
  75.             }  
  76.         }  
  77.         return 0;  
  78.     }  
  79.   
  80.     /** 
  81.      * 根据URL得到输入流 
  82.      *  
  83.      * @param urlStr 
  84.      * @return 
  85.      * @throws MalformedURLException 
  86.      * @throws IOException 
  87.      */  
  88.     public InputStream getInputStreamFromUrl(String urlStr)  
  89.             throws MalformedURLException, IOException {  
  90.         url = new URL(urlStr);  
  91.         HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  92.         InputStream inputStream = urlConn.getInputStream();  
  93.         return inputStream;  
  94.     }  
  95. }  
FileUtils.java
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.chay.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.         //得到当前外部存储设备的目录  
  19.         // /SDCARD  
  20.         SDPATH = Environment.getExternalStorageDirectory() + "/";  
  21.     }  
  22.     /** 
  23.      * 在SD卡上创建文件 
  24.      *  
  25.      * @throws IOException 
  26.      */  
  27.     public File creatSDFile(String fileName) throws IOException {  
  28.         File file = new File(SDPATH + fileName);  
  29.         file.createNewFile();  
  30.         return file;  
  31.     }  
  32.       
  33.     /** 
  34.      * 在SD卡上创建目录 
  35.      *  
  36.      * @param dirName 
  37.      */  
  38.     public File creatSDDir(String dirName) {  
  39.         File dir = new File(SDPATH + dirName);  
  40.         dir.mkdirs();  
  41.         return dir;  
  42.     }  
  43.   
  44.     /** 
  45.      * 判断SD卡上的文件夹是否存在 
  46.      */  
  47.     public boolean isFileExist(String fileName){  
  48.         File file = new File(SDPATH + fileName);  
  49.         return file.exists();  
  50.     }  
  51.       
  52.     /** 
  53.      * 将一个InputStream里面的数据写入到SD卡中 
  54.      */  
  55.     public File write2SDFromInput(String path,String fileName,InputStream input){  
  56.         File file = null;  
  57.         OutputStream output = null;  
  58.         try{  
  59.             creatSDDir(path);  
  60.             file = creatSDFile(path + fileName);  
  61.             output = new FileOutputStream(file);  
  62.             byte buffer [] = new byte[4 * 1024];  
  63.             while((input.read(buffer)) != -1){  
  64.                 output.write(buffer);  
  65.             }  
  66.             output.flush();  
  67.         }  
  68.         catch(Exception e){  
  69.             e.printStackTrace();  
  70.         }  
  71.         finally{  
  72.             try{  
  73.                 output.close();  
  74.             }  
  75.             catch(Exception e){  
  76.                 e.printStackTrace();  
  77.             }  
  78.         }  
  79.         return file;  
  80.     }  
  81. }  
 --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---


如果不能下载,请先将windows防火墙关闭。

欢迎交流 http://blog.csdn.net/ycwol/article/details/44546337


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值