Chinaunix首页 | 论坛 | 博客
  • 博客访问: 198410
  • 博文数量: 102
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1015
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-05 16:45
文章存档

2014年(73)

2013年(29)

我的朋友

分类: Android平台

2013-12-24 11:27:55

01_18_文件下载(HTTP协议下载(歌词+MP3)文件并写入SDCARD)
1、使用HTTP协议下载文件
2、将下载的文件写入SDCARD中

1、使用HTTP协议下载文件
    文件下载的步骤
       1. 创建
一个HttpURLConnection对象
            HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
       2. 获得一个InputStream对象
            urlConn.getInputStream()
        3.访问网络的权限
            android.permission.INTERNET

2、将下载的文件写入SDCARD中
    访问SDCARD
        1、得到当前设备SD卡的目录
            Environment.getExternalStorageDirectory();
        2、访问SD卡的权限
            android.permission.WRITE_EXTERNAL_STORAGE
3、这个过程可能遇到的问题

点击(此处)折叠或打开

  1. //Download.java
  2. package com.lwb.mydownload;

  3. import android.os.Bundle;
  4. import android.app.Activity;
  5. import android.view.Menu;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.widget.Button;

  9. public class MyDownload extends Activity {

  10.     private Button downloadTextButton;
  11.     private Button downloadMp3Button;
  12.     
  13.     @Override
  14.     protected void onCreate(Bundle savedInstanceState) {
  15.         super.onCreate(savedInstanceState);
  16.         setContentView(R.layout.main);
  17.         
  18.         downloadTextButton =(Button)findViewById(R.id.downloadText);
  19.         downloadMp3Button =(Button)findViewById(R.id.downloadMp3);
  20.         downloadTextButton.setOnClickListener(new DownloadTextListener());
  21.         downloadMp3Button.setOnClickListener(new DownloadMp3Listener());
  22.         
  23.     }
  24.     
  25.     class DownloadTextListener implements OnClickListener{
  26.         @Override
  27.         public void onClick(View v) {
  28.             // TODO Auto-generated method stub
  29.             //Tomcat 提供web服务
  30.             HttpDownloader httpDownloader =new HttpDownloader();
  31.             String lrc = httpDownloader.download("");
  32.             System.out.println(lrc);
  33.         }        
  34.     }
  35.     
  36.     class DownloadMp3Listener implements OnClickListener{

  37.         @Override
  38.         public void onClick(View v) {
  39.             // TODO Auto-generated method stub
  40.             HttpDownloader httpDownloader = new HttpDownloader();
  41.             String path = new String();
  42.             
  43.             int result = httpDownloader.downFile("", "mp3/" ,"aa1.mp3");
  44.             System.out.println(result);
  45.             
  46.         }        
  47.     }

  48.     @Override
  49.     public boolean onCreateOptionsMenu(Menu menu) {
  50.         // Inflate the menu; this adds items to the action bar if it is present.
  51.         getMenuInflater().inflate(R.menu.my_download, menu);
  52.         return true;
  53.     }

  54. }

点击(此处)折叠或打开

  1. //HttpDownloader.java 下载文件类
  2. package com.lwb.mydownload;

  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. public class HttpDownloader {
  12.     private URL url = null;
  13.     
  14.     /*根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件中内容
  15.      * 1、创建一个URL对象
  16.      * 2、通过URL对象,创建一个HttpURLConnection对象
  17.      * 3、得到InputStream
  18.      * 4、从InputSteam当中读取数据
  19.      * @param urlStr
  20.      * @return
  21.      * */
  22.     
  23.     public String download(String urlStr){
  24.         StringBuffer sb =new StringBuffer();
  25.         String line = null;
  26.         BufferedReader buffer = null; //IO流中经常使用的对象
  27.         
  28.         try{
  29.             //1、创建一个URL对象
  30.             url = new URL(urlStr);
  31.             //URL(Uniform Resource Locator:统一资源定位器)是WWW也的地址
  32.             
  33.             //2、创建一个Http链接
  34.             HttpURLConnection urlConn=(HttpURLConnection) url.openConnection();
  35.             
  36.             //3、使用IO流读取数据到InputStream
  37.             buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
  38.             //上面采用了装饰者设计模式:getInputSteam()字节流-》InputStreamReader()字符流-》
  39.             //Bufferedreader读取一行数据
  40.             
  41.             //4、从InputStream当中读取数据
  42.             while((line = buffer.readLine())!= null){
  43.                 sb.append(line);
  44.             }
  45.         }catch(Exception e){
  46.             e.printStackTrace();
  47.         }finally{
  48.             try{
  49.                 buffer.close();
  50.             }catch(Exception e){
  51.                 e.printStackTrace();
  52.             }
  53.         }
  54.         return sb.toString();
  55.     }
  56.     
  57.     /**
  58.      * 该函数返回整形 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在
  59.      */
  60.     //                         链接             目录                文件名
  61.     public int downFile(String urlStr,String path,String fileName){
  62.         StringBuffer sb = new StringBuffer();
  63.         InputStream inputStream = null;
  64.         
  65.         try{
  66.             //创建一个FileUtils类型的对象
  67.             FileUtils fileUtils = new FileUtils();
  68.             
  69.             //判断文件是否已经存在
  70.             if(fileUtils.isFileExist(path+fileName)){
  71.                 return 1;//表文件已存在
  72.             }
  73.             else{
  74.                 inputStream = getInputStreamFromUrl(urlStr);//调用下面的函数
  75.                 
  76.                 File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
  77.                 if(resultFile==null){
  78.                     return -1 ;//写入失败
  79.                 }
  80.             }
  81.         }
  82.         catch(Exception e){
  83.             e.printStackTrace();
  84.             return -1;
  85.         }
  86.         finally{
  87.             try{
  88.                 inputStream.close();                    
  89.             }catch(Exception e){
  90.                 e.printStackTrace();
  91.             }
  92.         }
  93.         return 0;
  94.     }
  95.         
  96.     /*根据URL得到输入流
  97.      * @param urlStr
  98.      * @return
  99.      * @throws MalformedURLException
  100.      * @throws IOException
  101.      */
  102.     public InputStream getInputStreamFromUrl(String urlStr)//返回输入流
  103.     throws MalformedURLException,IOException{
  104.         //1、创建一个URL对象
  105.         url = new URL(urlStr);
  106.         //2、创建一个Http链接
  107.         HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
  108.         //3.1使用IO流读取数据 得到InputStram
  109.         InputStream inputSteam = urlConn.getInputStream();
  110.         return inputSteam;
  111.     }
  112.     
  113.     
  114.     
  115. }


点击(此处)折叠或打开

  1. //FileUtils 写外部存储卡类
  2. package com.lwb.mydownload;

  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. import android.os.Environment;

  9. public class FileUtils {
  10.     private String SDPATH;
  11.     
  12.     public FileUtils(){
  13.         //得到当前外部存储设备目录 我的是/mnt/sdcard
  14.         SDPATH = Environment.getExternalStorageDirectory()+"/";
  15.     }
  16.     public String getSDPATH(){
  17.         return SDPATH;
  18.     }
  19.     
  20.     /*在SD卡上创建文件
  21.      * @throws IOException
  22.      */    
  23.     public File creatSDFile(String fileName) throws IOException{
  24.         File file = new File(SDPATH+fileName);
  25.         file.createNewFile();
  26.         return file;
  27.     }
  28.     
  29.     //    在SD卡上创建目录
  30.     public File creatSDDir(String dirName){
  31.         File dir = new File(SDPATH+dirName);
  32.         dir.mkdir();
  33.         return dir;
  34.     }
  35.     
  36.     //判断SD卡上的文件夹是否存在
  37.     public boolean isFileExist(String fileName){
  38.         File file = new File(SDPATH+fileName);
  39.         return file.exists();
  40.     }
  41.     
  42.     //将一个InputStream里面的数据写到SD卡中
  43.     public File write2SDFromInput(String path,String fileName,InputStream input){
  44.         File file = null;
  45.         OutputStream output = null;
  46.         try{
  47.             creatSDDir(path);//创建目录
  48.             file = creatSDFile(path+fileName);//创建文件
  49.             output = new FileOutputStream(file);//写入数据
  50.             byte buffer [] = new byte[4*1024];
  51.             while((input.read(buffer)!= -1)){
  52.                 output.write(buffer);
  53.             }
  54.             output.flush();//清空缓存            
  55.         }
  56.         catch(Exception e){
  57.             e.printStackTrace();
  58.         }
  59.             try{
  60.                 output.close();
  61.             }
  62.             catch(Exception e){
  63.                 e.printStackTrace();
  64.             }
  65.     
  66.         return file;
  67.     }
  68.     
  69.     
  70. }
重要的是要在AndroidManifest.xml添加如下代码:

点击(此处)折叠或打开

  1. <!-- 在下面一定记得添加 许可 uses-permission-->
  2.     <uses-permission android:name="android.permission.INTERNET"/>
  3.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  4. </manifest>







3、这个过程可能遇到的问题
   
问题1:
     Tomcat我安装的是:apache-tomcat-6.0.37

    配置Tomcat:

    把要下载的文件或文件夹放在安装目录下即可。我的是:D:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps
    

问题2:
    当cmd命令行下输入adb  shell可能出现adb shell errror:device not fount
    处理办法:
        adb kill-server
        adb start-server

问题3:
    写外部存储卡失败(上面的下载a1.mp3失败),原因是外部写储存卡没有写的权限。
    得添加权限,答案在:http://blog.csdn.net/mouttz/article/details/12911435

    模拟器中,sdcard可能是只读的。 

    在shell命令行中输入

    adb root

    切换到root用户

    然后执行如下命令:(注意,/表示的是根目录,因此这个不仅仅是对sdcard,其他文件也可以读写。rw表示读写权限,mount重挂载文件    系    统)

       adb shell mount -o remount rw / 

       执行完后,
    可以用mount命令查看,当前挂载的文件系统权限如何,可以看出都有读写权限了(rw)。

    # mount
        mount
        ……
        tmpfs /mnt/asec tmpfs rw,mode=755,gid=1000 0 0
        #

    然后用
    #chmod 777  /mnt/sdcard      
    好了,(我的外部存储卡目录 /mnt/sdcard)可写了


总结一下:linux下一定要注意读写执行权限的问题
                linux下一切设备皆文件(上面创建目录也是用文件File类的)


阅读(1383) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~