android开发之下载文本、音乐文件

来源:互联网 发布:vmware p2v迁移linux 编辑:程序博客网 时间:2024/05/21 08:37

今天和大家分享一下在android上怎么下载文件到手机上。

主要有两点大类容:

一,通过Http协议下载文件。

创建一个HttpURLConnection对象

[java] view plain copy
  1. HttpURLConnection urlConn = (HttpURLConnection) url  
  2.      .openConnection();  

 获得一个InputStream对象

[java] view plain copy
  1. inputStream = urlConn.getInputStream();  

访问网络的权限

[html] view plain copy
  1. <uses-permission android:name="android.permission.INTERNET"/>  



二,将下载的文件写入SDcard。

得到当前设备的SD卡目录

[java] view plain copy
  1. Environment.getExternalStorageDirectory()  

设置访问SD卡的权限

[html] view plain copy
  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  


下面给出具体的代码:

DownLoad.java

[java] view plain copy
  1. import android.app.Activity;  
  2. import android.os.Bundle;  
  3. import android.util.HttpDownloader;  
  4. import android.view.View;  
  5. import android.view.View.OnClickListener;  
  6. import android.widget.Button;  
  7.   
  8. public class DownLoad extends Activity {  
  9.     private Button textButton;  
  10.     private Button audioButton;  
  11.   
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);  
  16.         //文本下载  
  17.         textButton = (Button) findViewById(R.id.textButton);  
  18.         textButton.setOnClickListener(new OnClickListener() {  
  19.   
  20.             @Override  
  21.             public void onClick(View v) {  
  22.                 HttpDownloader http = new HttpDownloader();  
  23.                 //注意这里不要用localhost或者127.0.0.1,会报错的,因为android里是10.0.2.2  
  24.                 String txt = http  
  25.                         .download("http://10.0.2.2:8080/examples/123123.txt");  
  26.                 System.out.println(txt);  
  27.             }  
  28.         });  
  29.         //音频下载  
  30.         audioButton = (Button) findViewById(R.id.audioButton);  
  31.         audioButton.setOnClickListener(new OnClickListener() {  
  32.   
  33.             @Override  
  34.             public void onClick(View v) {  
  35.                 HttpDownloader http = new HttpDownloader();  
  36.                 String result = http.download(  
  37.                         "http://10.0.2.2:8080/examples/123.mp3""/music",  
  38.                         "zhou.mp3");  
  39.                 System.out.println(result);  
  40.             }  
  41.         });  
  42.   
  43.     }  
  44. }  

FileUtil.java

[java] view plain copy
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6.   
  7. import android.os.Environment;  
  8.   
  9. public class FileUtil {  
  10.     private String SDCARDPATH;  
  11.   
  12.     public String getSDCARDPATH() {  
  13.         return SDCARDPATH;  
  14.     }  
  15.   
  16.     public FileUtil() {  
  17.         // 得到手机存储器目录---因为各个厂商的手机SDcard可能不一样,最好不要写死了  
  18.         SDCARDPATH = Environment.getExternalStorageDirectory() + "/";  
  19.     }  
  20.   
  21.     /** 
  22.      * 在SDcard上创建文件 
  23.      *  
  24.      * @param fileName 
  25.      * @return File 
  26.      */  
  27.     public File creatSDFile(String fileName) {  
  28.         File file = new File(SDCARDPATH + fileName);  
  29.         return file;  
  30.     }  
  31.   
  32.     /** 
  33.      * 在SDcard上创建目录 
  34.      *  
  35.      * @param dirName 
  36.      */  
  37.     public void createSDDir(String dirName) {  
  38.         File file = new File(SDCARDPATH + dirName);  
  39.         file.mkdir();  
  40.     }  
  41.   
  42.     /** 
  43.      * 判断文件是否存在 
  44.      *  
  45.      * @param fileName 
  46.      * @return boolean 
  47.      */  
  48.     public boolean isFileExist(String fileName) {  
  49.         File file = new File(SDCARDPATH + fileName);  
  50.         return file.exists();  
  51.     }  
  52.   
  53.     /** 
  54.      * @param path 
  55.      *            存放目录 
  56.      * @param fileName 
  57.      *            文件名字 
  58.      * @param input 
  59.      *            数据来源 
  60.      * @return 
  61.      */  
  62.     public File writeToSDCard(String path, String fileName, InputStream input) {  
  63.         File file = null;  
  64.         OutputStream output = null;  
  65.         try {  
  66.             //创建路径  
  67.             createSDDir(path);  
  68.             //创建文件  
  69.             file = creatSDFile(path + fileName);  
  70.             output = new FileOutputStream(file);  
  71.             //以4K为单位,每次写4k  
  72.             byte buffer[] = new byte[4 * 1024];  
  73.             while ((input.read(buffer)) != -1) {  
  74.                 output.write(buffer);  
  75.             }  
  76.             // 清除缓存  
  77.             output.flush();  
  78.         } catch (IOException e) {  
  79.             e.printStackTrace();  
  80.         } finally {  
  81.             try {  
  82.                 // 关闭流  
  83.                 output.close();  
  84.             } catch (IOException e) {  
  85.                 e.printStackTrace();  
  86.             }  
  87.         }  
  88.         return file;  
  89.     }  
  90. }  

HttpDownloader.java

[java] view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.MalformedURLException;  
  8. import java.net.URL;  
  9.   
  10. public class HttpDownloader {  
  11.     private URL url = null;  
  12.   
  13.     /** 
  14.      * 下载文本文件 
  15.      *  
  16.      * @param urlStr 
  17.      * @return 
  18.      */  
  19.     public String download(String urlStr) {  
  20.         StringBuffer sb = new StringBuffer();  
  21.         String line = null;  
  22.         BufferedReader buffer = null;  
  23.         try {  
  24.             buffer = new BufferedReader(new InputStreamReader(  
  25.                     getInputStreamFromUrl(urlStr)));  
  26.             //一行一行的读取  
  27.             while ((line = buffer.readLine()) != null) {  
  28.                 sb.append(line);  
  29.             }  
  30.         } catch (Exception e) {  
  31.             e.printStackTrace();  
  32.         } finally {  
  33.             try {  
  34.                 buffer.close();  
  35.             } catch (IOException e) {  
  36.                 e.printStackTrace();  
  37.             }  
  38.         }  
  39.         return sb.toString();  
  40.     }  
  41.   
  42.     /** 
  43.      * @param urlStr 
  44.      *            文件所在的网络地址 
  45.      * @param path 
  46.      *            存储的目录 
  47.      * @param fileName 
  48.      *            存放的文件名 
  49.      * @return 状态 
  50.      */  
  51.     public String download(String urlStr, String path, String fileName) {  
  52.         InputStream inputStream = null;  
  53.         try {  
  54.             FileUtil fileUtils = new FileUtil();  
  55.             //判断文件是否已存在  
  56.             if (fileUtils.isFileExist(path + fileName)) {  
  57.                 return "fileExist";  
  58.             } else {  
  59.                 inputStream = getInputStreamFromUrl(urlStr);  
  60.                 File resultFile = fileUtils.writeToSDCard(path, fileName,  
  61.                         inputStream);  
  62.                 //如果resultFile==null则下载失败  
  63.                 if (resultFile == null) {  
  64.                     return "downloadError";  
  65.                 }  
  66.             }  
  67.         } catch (Exception e) {  
  68.             //如果异常了,也下载失败  
  69.             e.printStackTrace();  
  70.             return "downloadError";  
  71.         } finally {  
  72.             try {  
  73.                 //别忘了关闭流  
  74.                 inputStream.close();  
  75.             } catch (IOException e) {  
  76.                 e.printStackTrace();  
  77.             }  
  78.         }  
  79.         return "downloadOk";  
  80.   
  81.     }  
  82.   
  83.     /** 
  84.      * 连接到网络( 抽取的公共方法) 
  85.      *  
  86.      * @param urlStr 
  87.      *            文件所在的网络地址 
  88.      * @return InputStream 
  89.      */  
  90.     public InputStream getInputStreamFromUrl(String urlStr) {  
  91.         InputStream inputStream = null;  
  92.         try {  
  93.             // 创建一个URL对象  
  94.             url = new URL(urlStr);  
  95.             // 根据URL对象创建一个HttpURLConnection连接  
  96.             HttpURLConnection urlConn = (HttpURLConnection) url  
  97.                     .openConnection();  
  98.             // IO流读取数据  
  99.             inputStream = urlConn.getInputStream();  
  100.         } catch (MalformedURLException e) {  
  101.             e.printStackTrace();  
  102.         } catch (IOException e) {  
  103.             e.printStackTrace();  
  104.         }  
  105.         return inputStream;  
  106.     }  
  107.   
  108. }  

AndroidManifest.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="android.apps"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.   
  7.   
  8.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  9.         <activity android:name=".DownLoad"  
  10.                   android:label="@string/app_name">  
  11.             <intent-filter>  
  12.                 <action android:name="android.intent.action.MAIN" />  
  13.                 <category android:name="android.intent.category.LAUNCHER" />  
  14.             </intent-filter>  
  15.         </activity>  
  16.   
  17.     </application>  
  18.     <!-- 连接到网络的权限 -->  
  19.     <uses-permission android:name="android.permission.INTERNET"/>  
  20.     <!-- 访问SDcard的权限 -->  
  21.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  22. </manifest>  


希望对大家有帮助。

1 0
原创粉丝点击