`
wsql
  • 浏览: 11715143 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Android 下载文件及写入SD卡

 
阅读更多

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

Main.xml代码 收藏代码
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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>

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

下载助手类httpdownloader 代码 收藏代码
  1. packagecom.learning.example.util;
  2. importjava.io.BufferedReader;
  3. importjava.io.File;
  4. importjava.io.IOException;
  5. importjava.io.InputStream;
  6. importjava.io.InputStreamReader;
  7. importjava.net.HttpURLConnection;
  8. importjava.net.MalformedURLException;
  9. importjava.net.URL;
  10. publicclassHttpDownloader{
  11. privateURLurl=null;
  12. /**
  13. *根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容
  14. *1.创建一个URL对象
  15. *2.通过URL对象,创建一个HttpURLConnection对象
  16. *3.得到InputStream
  17. *4.从InputStream当中读取数据
  18. *@paramurlStr
  19. *@return
  20. */
  21. publicStringdownload(StringurlStr){
  22. StringBuffersb=newStringBuffer();
  23. Stringline=null;
  24. BufferedReaderbuffer=null;
  25. try{
  26. url=newURL(urlStr);

  27. HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();
  28. buffer=newBufferedReader(newInputStreamReader(urlConn.getInputStream()));
  29. while((line=buffer.readLine())!=null){
  30. sb.append(line);
  31. }
  32. }
  33. catch(Exceptione){
  34. e.printStackTrace();
  35. }
  36. finally{
  37. try{
  38. buffer.close();
  39. }catch(IOExceptione){
  40. e.printStackTrace();
  41. }
  42. }
  43. returnsb.toString();
  44. }
  45. /**
  46. *
  47. *@paramurlStr
  48. *@parampath
  49. *@paramfileName
  50. *@return
  51. *-1:文件下载出错
  52. *0:文件下载成功
  53. *1:文件已经存在
  54. */
  55. publicintdownFile(StringurlStr,Stringpath,StringfileName){
  56. InputStreaminputStream=null;
  57. try{
  58. FileUtilsfileUtils=newFileUtils();
  59. if(fileUtils.isFileExist(path+fileName)){
  60. return1;
  61. }else{
  62. inputStream=getInputStreamFromURL(urlStr);
  63. FileresultFile=fileUtils.write2SDFromInput(path,fileName,inputStream);
  64. if(resultFile==null){
  65. return-1;
  66. }
  67. }
  68. }
  69. catch(Exceptione){
  70. e.printStackTrace();
  71. return-1;
  72. }
  73. finally{
  74. try{
  75. inputStream.close();
  76. }catch(IOExceptione){
  77. e.printStackTrace();
  78. }
  79. }
  80. return0;
  81. }
  82. /**
  83. *根据URL得到输入流
  84. *@paramurlStr
  85. *@return
  86. */
  87. publicInputStreamgetInputStreamFromURL(StringurlStr){
  88. HttpURLConnectionurlConn=null;
  89. InputStreaminputStream=null;
  90. try{
  91. url=newURL(urlStr);
  92. urlConn=(HttpURLConnection)url.openConnection();
  93. inputStream=urlConn.getInputStream();
  94. }catch(MalformedURLExceptione){
  95. e.printStackTrace();
  96. }catch(IOExceptione){
  97. e.printStackTrace();
  98. }
  99. returninputStream;
  100. }
  101. }

文件操作类fileutils 代码 收藏代码
  1. packagecom.learning.example.util;
  2. importjava.io.File;
  3. importjava.io.FileOutputStream;
  4. importjava.io.IOException;
  5. importjava.io.InputStream;
  6. importjava.io.OutputStream;
  7. importandroid.os.Environment;
  8. publicclassFileUtils{
  9. privateStringSDPATH;
  10. privateintFILESIZE=4*1024;
  11. publicStringgetSDPATH(){
  12. returnSDPATH;
  13. }
  14. publicFileUtils(){
  15. //得到当前外部存储设备的目录(/SDCARD)
  16. SDPATH=Environment.getExternalStorageDirectory()+"/";
  17. }
  18. /**
  19. *在SD卡上创建文件
  20. *@paramfileName
  21. *@return
  22. *@throwsIOException
  23. */
  24. publicFilecreateSDFile(StringfileName)throwsIOException{
  25. Filefile=newFile(SDPATH+fileName);
  26. file.createNewFile();
  27. returnfile;
  28. }
  29. /**
  30. *在SD卡上创建目录
  31. *@paramdirName
  32. *@return
  33. */
  34. publicFilecreateSDDir(StringdirName){
  35. Filedir=newFile(SDPATH+dirName);
  36. dir.mkdir();
  37. returndir;
  38. }
  39. /**
  40. *判断SD卡上的文件夹是否存在
  41. *@paramfileName
  42. *@return
  43. */
  44. publicbooleanisFileExist(StringfileName){
  45. Filefile=newFile(SDPATH+fileName);
  46. returnfile.exists();
  47. }
  48. /**
  49. *将一个InputStream里面的数据写入到SD卡中
  50. *@parampath
  51. *@paramfileName
  52. *@paraminput
  53. *@return
  54. */
  55. publicFilewrite2SDFromInput(Stringpath,StringfileName,InputStreaminput){
  56. Filefile=null;
  57. OutputStreamoutput=null;
  58. try{
  59. createSDDir(path);
  60. int count = 0 ;
  61. file=createSDFile(path+fileName);
  62. output=newFileOutputStream(file);
  63. byte[]buffer=newbyte[FILESIZE];
  64. while((count=input.read(buffer))!=-1){
  65. output.write(buffer,0,count);
  66. }
  67. output.flush();
  68. }
  69. catch(Exceptione){
  70. e.printStackTrace();
  71. }
  72. finally{
  73. try{
  74. output.close();
  75. }catch(IOExceptione){
  76. e.printStackTrace();
  77. }
  78. }
  79. returnfile;
  80. }
  81. }

主程序类download 代码 收藏代码
  1. packagecom.learning.example;
  2. importcom.learning.example.util.HttpDownloader;
  3. importandroid.app.Activity;
  4. importandroid.os.Bundle;
  5. importandroid.view.View;
  6. importandroid.view.View.OnClickListener;
  7. importandroid.widget.Button;
  8. publicclassDownloadextendsActivity{
  9. privateButtondownlaodTxtButton;
  10. privateButtondownlaodMP3Button;
  11. @Override
  12. publicvoidonCreate(BundlesavedInstanceState){
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.main);
  15. downlaodTxtButton=(Button)findViewById(R.id.downloadTxt);
  16. downlaodTxtButton.setOnClickListener(newDownloadTxtListener());
  17. downlaodMP3Button=(Button)findViewById(R.id.downloadMp3);
  18. downlaodMP3Button.setOnClickListener(newDownloadMP3Listener());
  19. }
  20. classDownloadTxtListenerimplementsOnClickListener{
  21. @Override
  22. publicvoidonClick(Viewv){
  23. HttpDownloaderdownloader=newHttpDownloader();
  24. Stringlrc=downloader.download("http://172.16.11.9:8080/test/1.lrc");
  25. System.out.println(lrc);
  26. }
  27. }
  28. classDownloadMP3ListenerimplementsOnClickListener{
  29. @Override
  30. publicvoidonClick(Viewv){
  31. HttpDownloaderdownloader=newHttpDownloader();
  32. intresult=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"/>


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics