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

  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. <Button
  14. android:id="@+id/downloadMp3"
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content"
  17. android:text="下载MP3文件"
  18. />
  19. </LinearLayout>
  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. </application>
  15. <uses-sdk android:minSdkVersion="8" />
  16. <!-- 访问网络和操作SD卡 加入的两个权限配置-->
  17. <uses-permission android:name="android.permission.INTERNET"/>
  18. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  19. </manifest>
  1. package com.learning.example.util;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. public class HttpDownloader {
  11. private URL url = null;
  12. /**
  13. * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容
  14. * 1.创建一个URL对象
  15. * 2.通过URL对象,创建一个HttpURLConnection对象
  16. * 3.得到InputStream
  17. * 4.从InputStream当中读取数据
  18. * @param urlStr
  19. * @return
  20. */
  21. public String download(String urlStr){
  22. StringBuffer sb = new StringBuffer();
  23. String line = null;
  24. BufferedReader buffer = null;
  25. try {
  26. url = new URL(urlStr);
  27. HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
  28. buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
  29. while( (line = buffer.readLine()) != null){
  30. sb.append(line);
  31. }
  32. }
  33. catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. finally{
  37. try {
  38. buffer.close();
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. return sb.toString();
  44. }
  45. /**
  46. *
  47. * @param urlStr
  48. * @param path
  49. * @param fileName
  50. * @return
  51. *      -1:文件下载出错
  52. *       0:文件下载成功
  53. *       1:文件已经存在
  54. */
  55. public int downFile(String urlStr, String path, String fileName){
  56. InputStream inputStream = null;
  57. try {
  58. FileUtils fileUtils = new FileUtils();
  59. if(fileUtils.isFileExist(path + fileName)){
  60. return 1;
  61. } else {
  62. inputStream = getInputStreamFromURL(urlStr);
  63. File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
  64. if(resultFile == null){
  65. return -1;
  66. }
  67. }
  68. }
  69. catch (Exception e) {
  70. e.printStackTrace();
  71. return -1;
  72. }
  73. finally{
  74. try {
  75. inputStream.close();
  76. } catch (IOException e) {
  77. e.printStackTrace();
  78. }
  79. }
  80. return 0;
  81. }
  82. /**
  83. * 根据URL得到输入流
  84. * @param urlStr
  85. * @return
  86. */
  87. public InputStream getInputStreamFromURL(String urlStr) {
  88. HttpURLConnection urlConn = null;
  89. InputStream inputStream = null;
  90. try {
  91. url = new URL(urlStr);
  92. urlConn = (HttpURLConnection)url.openConnection();
  93. inputStream = urlConn.getInputStream();
  94. } catch (MalformedURLException e) {
  95. e.printStackTrace();
  96. } catch (IOException e) {
  97. e.printStackTrace();
  98. }
  99. return inputStream;
  100. }
  101. }
  1. package com.learning.example.util;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import android.os.Environment;
  8. public class FileUtils {
  9. private String SDPATH;
  10. private int FILESIZE = 4 * 1024;
  11. public String getSDPATH(){
  12. return SDPATH;
  13. }
  14. public FileUtils(){
  15. //得到当前外部存储设备的目录( /SDCARD )
  16. SDPATH = Environment.getExternalStorageDirectory() + "/";
  17. }
  18. /**
  19. * 在SD卡上创建文件
  20. * @param fileName
  21. * @return
  22. * @throws IOException
  23. */
  24. public File createSDFile(String fileName) throws IOException{
  25. File file = new File(SDPATH + fileName);
  26. file.createNewFile();
  27. return file;
  28. }
  29. /**
  30. * 在SD卡上创建目录
  31. * @param dirName
  32. * @return
  33. */
  34. public File createSDDir(String dirName){
  35. File dir = new File(SDPATH + dirName);
  36. dir.mkdir();
  37. return dir;
  38. }
  39. /**
  40. * 判断SD卡上的文件夹是否存在
  41. * @param fileName
  42. * @return
  43. */
  44. public boolean isFileExist(String fileName){
  45. File file = new File(SDPATH + fileName);
  46. return file.exists();
  47. }
  48. /**
  49. * 将一个InputStream里面的数据写入到SD卡中
  50. * @param path
  51. * @param fileName
  52. * @param input
  53. * @return
  54. */
  55. public File write2SDFromInput(String path,String fileName,InputStream input){
  56. File file = null;
  57. OutputStream output = null;
  58. try {
  59. createSDDir(path);
  60. file = createSDFile(path + fileName);
  61. output = new FileOutputStream(file);
  62. byte[] buffer = new byte[FILESIZE];
  63. /*真机测试,这段可能有问题,请采用下面网友提供的
  64. while((input.read(buffer)) != -1){
  65. output.write(buffer);
  66. }
  67. */
  68. /* 网友提供 begin */
  69. int length;
  70. while((length=(input.read(buffer))) >0){
  71. output.write(buffer,0,length);
  72. }
  73. /* 网友提供 end */
  74. output.flush();
  75. }
  76. catch (Exception e) {
  77. e.printStackTrace();
  78. }
  79. finally{
  80. try {
  81. output.close();
  82. } catch (IOException e) {
  83. e.printStackTrace();
  84. }
  85. }
  86. return file;
  87. }
  88. }
  1. package com.learning.example;
  2. import com.learning.example.util.HttpDownloader;
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. public class Download extends Activity {
  9. private Button downlaodTxtButton ;
  10. private Button downlaodMP3Button ;
  11. @Override
  12. public void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.main);
  15. downlaodTxtButton = (Button)findViewById(R.id.downloadTxt);
  16. downlaodTxtButton.setOnClickListener(new DownloadTxtListener());
  17. downlaodMP3Button = (Button)findViewById(R.id.downloadMp3);
  18. downlaodMP3Button.setOnClickListener(new DownloadMP3Listener());
  19. }
  20. class DownloadTxtListener implements OnClickListener{
  21. @Override
  22. public void onClick(View v) {
  23. HttpDownloader downloader = new HttpDownloader();
  24. String lrc = downloader.download("http://172.16.11.9:8080/test/1.lrc");
  25. System.out.println(lrc);
  26. }
  27. }
  28. class DownloadMP3Listener implements OnClickListener{
  29. @Override
  30. public void onClick(View v) {
  31. HttpDownloader downloader = new HttpDownloader();
  32. int result = downloader.downFile("http://172.16.11.9:8080/test/1.mp3", "voa/", "1.map3");
  33. System.out.println(result);
  34. }
  35. }
  36. }

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

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

Android 下载文件及写入SD卡的更多相关文章

  1. Android从网络某个地址下载文件、写入SD卡

    首先创建一个HttpDownloader类,获取下载文件的网络地址,将文件下载下来以String流的方式返回: public String download(String urlStr){ //url ...

  2. Android 将文件保存到SD卡中

    ①写文件到sd卡中需要获得权限,在AndroidManifest.xml中添加如下权限: <uses-permission android:name="android.permissi ...

  3. Android 将文件保存到SD卡,从卡中取文件,及删除文件

    //保存到SD卡 private static String sdState = Environment.getExternalStorageState();     private static S ...

  4. Android根据URL下载文件保存到SD卡

    //下载具体操作 private void download() { try { URL url = new URL(downloadUrl); //打开连接 URLConnection conn = ...

  5. 转 Android:文件下载和写入SD卡学习小结

    转自 http://blog.csdn.net/zzp_403184692/article/details/8160739  一.文件下载  Android开发中,有时需要从网上下载一些资源以供用户使 ...

  6. [置顶] Android学习系列-把文件保存到SD卡上面(6)

    Android学习系列-把文件保存到SD卡上面(5) 一般多媒体文件,大文件需要保存到SD卡中.关键点如下: 1,SD卡保存目录:mnt/sdcard,一般采用Environment.getExter ...

  7. android学习笔记47——读写SD卡上的文件

    读写SD卡上的文件 通过Context的openFileInput.openFileOutput来打开文件输入流.输出流时,程序打开的都是应用程序的数据文件夹里的文件,其存储的文件大小可能都比较有限- ...

  8. assets下的文件复制到SD卡

    由于assets和res下的文件都只可以读不可以写,那么在程序初始化后,将后期需要使用并且需要修改的文件复制到SD卡.下面代码提供一个工具类,将assets下的任意资源复制到SD卡下. assets下 ...

  9. asserts文件存到外部SD卡里

    package com.example.wang.testapp3; import android.content.res.AssetManager; import android.graphics. ...

随机推荐

  1. javax.servlet.ServletException: com.microsoft.jdbc.base.BaseDatabaseMetaData.supportsGetGeneratedKeys()Z

    javax.servlet.ServletException: com.microsoft.jdbc.base.BaseDatabaseMetaData.supportsGetGeneratedKey ...

  2. Spring MVC框架

    这个Spring Web MVC 框架提供了模型视图控制器的架构,这种结构能够被用来开发灵活的和松耦合的Web应用程序. 这种MVC模式能够将应用程序分离成不同的层面,(输入逻辑,业务逻辑,UI逻辑) ...

  3. Xunit

    Attributes Note: This table was written back when xUnit.net 1.0 has shipped, and needs to be updated ...

  4. .net架构设计读书笔记--第一章 基础

    第一章 基础 第一节 软件架构与软件架构师  简单的说软件架构即是为客户构建一个软件系统.架构师随便软件架构应运而生,架构师是一个角色. 2000年9月ANSI和IEEE发布了<密集性软件架构建 ...

  5. javascript 规范

    关于变量及方法等的命名,没有硬性规定,但是为了规范,遵循一些约定还是有必要的. 变量定义: 用var 关键字将要使用的变量定义在代码开头,变量间用分号隔开. 原因有二: 一是便于理解,知道下面的代码会 ...

  6. 【BZOJ-2434】阿狸的打字机 AC自动机 + Fail树 + DFS序 + 树状数组

    2434: [Noi2011]阿狸的打字机 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 2022  Solved: 1158[Submit][Sta ...

  7. 【poj1274】 The Perfect Stall

    http://poj.org/problem?id=1274 (题目链接) 题意 懒得写了 Solution 二分图匹配裸题.注意清空数组. 代码 // poj3020 #include<alg ...

  8. 【poj1236】 Network of Schools

    http://poj.org/problem?id=1236 (题目链接) 题意 给定一个有向图,求:1.至少要选几个顶点,才能做到从这些顶点出发,可以到达全部顶点:2.至少要加多少条边,才能使得从任 ...

  9. CVE-2014-4877 && wget: FTP Symlink Arbitrary Filesystem Access

    目录 . 漏洞基本描述 . 漏洞带来的影响 . 漏洞攻击场景重现 . 漏洞的利用场景 . 漏洞原理分析 . 漏洞修复方案 . 攻防思考 1. 漏洞基本描述 0x1: Wget简介 wget是一个从网络 ...

  10. boost解析json

    #include <QtCore/QCoreApplication> #include <boost/property_tree/ptree.hpp> #include < ...