Android 下载文件及写入SD卡

简介: 引用:http://zhoujingxian.iteye.com/blog/859597 Android 下载文件及写入SD卡,实例代码   Main.xml代码                       Androidmanifest.

引用:http://zhoujingxian.iteye.com/blog/859597

Android 下载文件及写入SD卡,实例代码

 

Main.xml代码 
  收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <Button    
  8.     android:id="@+id/downloadTxt"  
  9.     android:layout_width="fill_parent"   
  10.     android:layout_height="wrap_content"   
  11.     android:text="下载文本文件"  
  12.     />  
  13.   
  14. <Button    
  15.     android:id="@+id/downloadMp3"  
  16.     android:layout_width="fill_parent"   
  17.     android:layout_height="wrap_content"   
  18.     android:text="下载MP3文件"  
  19.     />  
  20. </LinearLayout>  

 

Androidmanifest.xml代码 
  收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.learning.example"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".Download"  
  8.                   android:label="@string/app_name">  
  9.             <intent-filter>  
  10.                 <action android:name="android.intent.action.MAIN" />  
  11.                 <category android:name="android.intent.category.LAUNCHER" />  
  12.             </intent-filter>  
  13.         </activity>  
  14.   
  15.     </application>  
  16.     <uses-sdk android:minSdkVersion="8" />  
  17.   
  18. <!-- 访问网络和操作SD卡 加入的两个权限配置-->  
  19. <uses-permission android:name="android.permission.INTERNET"/>  
  20. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  21. </manifest>   

 

下载助手类httpdownloader 代码 
  收藏代码
  1. package com.learning.example.util;  
  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.       
  14.     private URL url = null;   
  15.       
  16.     /**  
  17.      * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容  
  18.      * 1.创建一个URL对象  
  19.      * 2.通过URL对象,创建一个HttpURLConnection对象  
  20.      * 3.得到InputStream  
  21.      * 4.从InputStream当中读取数据  
  22.      * @param urlStr  
  23.      * @return  
  24.      */  
  25.     public String download(String urlStr){  
  26.         StringBuffer sb = new StringBuffer();  
  27.         String line = null;  
  28.         BufferedReader buffer = null;  
  29.         try {  
  30.             url = new URL(urlStr);  
  31.             HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();  
  32.             buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));  
  33.             while( (line = buffer.readLine()) != null){  
  34.                 sb.append(line);  
  35.             }  
  36.               
  37.         }   
  38.         catch (Exception e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.         finally{  
  42.             try {  
  43.                 buffer.close();  
  44.             } catch (IOException e) {  
  45.                 e.printStackTrace();  
  46.             }  
  47.         }  
  48.         return sb.toString();  
  49.     }  
  50.   
  51.     /**  
  52.      *   
  53.      * @param urlStr  
  54.      * @param path  
  55.      * @param fileName  
  56.      * @return   
  57.      *      -1:文件下载出错  
  58.      *       0:文件下载成功  
  59.      *       1:文件已经存在  
  60.      */  
  61.     public int downFile(String urlStr, String path, String fileName){  
  62.         InputStream inputStream = null;  
  63.         try {  
  64.             FileUtils fileUtils = new FileUtils();  
  65.               
  66.             if(fileUtils.isFileExist(path + fileName)){  
  67.                 return 1;  
  68.             } else {  
  69.                 inputStream = getInputStreamFromURL(urlStr);  
  70.                 File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);  
  71.                 if(resultFile == null){  
  72.                     return -1;  
  73.                 }  
  74.             }  
  75.         }   
  76.         catch (Exception e) {  
  77.             e.printStackTrace();  
  78.             return -1;  
  79.         }  
  80.         finally{  
  81.             try {  
  82.                 inputStream.close();  
  83.             } catch (IOException e) {  
  84.                 e.printStackTrace();  
  85.             }  
  86.         }  
  87.         return 0;  
  88.     }  
  89.       
  90.     /**  
  91.      * 根据URL得到输入流  
  92.      * @param urlStr  
  93.      * @return  
  94.      */  
  95.     public InputStream getInputStreamFromURL(String urlStr) {  
  96.         HttpURLConnection urlConn = null;  
  97.         InputStream inputStream = null;  
  98.         try {  
  99.             url = new URL(urlStr);  
  100.             urlConn = (HttpURLConnection)url.openConnection();  
  101.             inputStream = urlConn.getInputStream();  
  102.               
  103.         } catch (MalformedURLException e) {  
  104.             e.printStackTrace();  
  105.         } catch (IOException e) {  
  106.             e.printStackTrace();  
  107.         }  
  108.           
  109.         return inputStream;  
  110.     }  
  111. }  

 

文件操作类fileutils 代码 
  收藏代码
  1. package com.learning.example.util;  
  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.     private int FILESIZE = 4 * 1024;   
  15.       
  16.     public String getSDPATH(){  
  17.         return SDPATH;  
  18.     }  
  19.       
  20.     public FileUtils(){  
  21.         //得到当前外部存储设备的目录( /SDCARD )  
  22.         SDPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";  
  23.     }  
  24.       
  25.     /**  
  26.      * 在SD卡上创建文件  
  27.      * @param fileName  
  28.      * @return  
  29.      * @throws IOException  
  30.      */  
  31.     public File createSDFile(String fileName) throws IOException{  
  32.         File file = new File(SDPATH + fileName);  
  33.         file.createNewFile();  
  34.         return file;  
  35.     }  
  36.       
  37.     /**  
  38.      * 在SD卡上创建目录  
  39.      * @param dirName  
  40.      * @return  
  41.      */  
  42.     public File createSDDir(String dirName){  
  43.         File dir = new File(SDPATH + dirName);  
  44.         dir.mkdir();  
  45.         return dir;  
  46.     }  
  47.       
  48.     /**  
  49.      * 判断SD卡上的文件夹是否存在  
  50.      * @param fileName  
  51.      * @return  
  52.      */  
  53.     public boolean isFileExist(String fileName){  
  54.         File file = new File(SDPATH + fileName);  
  55.         return file.exists();  
  56.     }  
  57.       
  58.     /**  
  59.      * 将一个InputStream里面的数据写入到SD卡中  
  60.      * @param path  
  61.      * @param fileName  
  62.      * @param input  
  63.      * @return  
  64.      */  
  65.     public File write2SDFromInput(String path,String fileName,InputStream input){  
  66.         File file = null;  
  67.         OutputStream output = null;  
  68.         try {  
  69.             createSDDir(path);  
  70.             file = createSDFile(path + fileName);  
  71.             output = new FileOutputStream(file);  
  72.             byte[] buffer = new byte[FILESIZE];  
  73.             while((input.read(buffer)) != -1){  
  74.                 output.write(buffer);  
  75.             }  
  76.             output.flush();  
  77.         }   
  78.         catch (Exception e) {  
  79.             e.printStackTrace();  
  80.         }  
  81.         finally{  
  82.             try {  
  83.                 output.close();  
  84.             } catch (IOException e) {  
  85.                 e.printStackTrace();  
  86.             }  
  87.         }  
  88.         return file;  
  89.     }  
  90.   
  91. }  

 

主程序类download 代码 
  收藏代码
  1. package com.learning.example;  
  2.   
  3. import com.learning.example.util.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 Download extends Activity {  
  12.     private Button downlaodTxtButton ;  
  13.     private Button downlaodMP3Button ;  
  14.       
  15.     @Override  
  16.     public void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.main);  
  19.         downlaodTxtButton = (Button)findViewById(R.id.downloadTxt);  
  20.         downlaodTxtButton.setOnClickListener(new DownloadTxtListener());  
  21.           
  22.         downlaodMP3Button = (Button)findViewById(R.id.downloadMp3);  
  23.         downlaodMP3Button.setOnClickListener(new DownloadMP3Listener());  
  24.     }  
  25.       
  26.     class DownloadTxtListener implements OnClickListener{  
  27.   
  28.         @Override  
  29.         public void onClick(View v) {  
  30.             HttpDownloader downloader = new HttpDownloader();  
  31.             String lrc = downloader.download("http://172.16.11.9:8080/test/1.lrc");  
  32.             System.out.println(lrc);  
  33.         }  
  34.           
  35.     }  
  36.       
  37.     class DownloadMP3Listener implements OnClickListener{  
  38.   
  39.         @Override  
  40.         public void onClick(View v) {  
  41.             HttpDownloader downloader = new HttpDownloader();  
  42.             int result = downloader.downFile("http://172.16.11.9:8080/test/1.mp3""voa/""1.map3");  
  43.             System.out.println(result);  
  44.         }  
  45.           
  46.     }  
  47. }  

Notice:访问网络和操作SD卡 记得加入的两个权限配置

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

相关文章
|
2月前
|
Android开发
安卓SO层开发 -- 编译指定平台的SO文件
安卓SO层开发 -- 编译指定平台的SO文件
30 0
|
4月前
|
开发工具 Android开发 开发者
Android Studio详细下载,安装使用教程
Android Studio详细下载,安装使用教程
297 0
|
4月前
|
XML Java Android开发
Android App开发网络通信中使用okhttp下载和上传图片、文件讲解及实战(超详细实现用户注册信息上传 附源码)
Android App开发网络通信中使用okhttp下载和上传图片、文件讲解及实战(超详细实现用户注册信息上传 附源码)
131 0
|
1月前
|
Shell 开发工具 Android开发
ADB 下载、安装及使用教程:让你更好地管理 Android 设备
ADB 下载、安装及使用教程:让你更好地管理 Android 设备
451 2
|
1月前
|
Android开发 对象存储
OSS对象储存android开发进行下载到本地文件时异步操作失效
android vivo80使用官方示例代码进行文件下载,但是使用oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>()时onSuccess和onFailure不执行
|
2月前
|
JSON Java Go
|
2月前
|
算法 Java Android开发
安卓逆向 -- 调用其他APK的SO文件
安卓逆向 -- 调用其他APK的SO文件
17 0
|
2月前
|
Android开发
安卓逆向 -- Hook多个dex文件
安卓逆向 -- Hook多个dex文件
18 1
|
3月前
|
IDE 开发工具 Android开发
Android Studio 下发布项目成APK文件
Android Studio 下发布项目成APK文件
117 1
|
3月前
|
安全 Android开发 数据安全/隐私保护
安卓逆向 -- SO文件逆向分析
安卓逆向 -- SO文件逆向分析
19 0