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

   首先创建一个HttpDownloader类,获取下载文件的网络地址,将文件下载下来以String流的方式返回:

    public String download(String urlStr){

      //urlStr为文件的网络地址,如http://192.168.1.105:8080/mp3/resources.xml
      StringBuffer sb = new StringBuffer();
      String line = null;
      BufferedReader buffer = null;
      try
      {
        //创建一个URL对象
        url = new URL(urlStr);
        //创建一个Http连接
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        //使用IO流读取数据
        buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        while((line = buffer.readLine()) != null){
          sb.append(line);
        }
      }
      catch(Exception ex){
        ex.printStackTrace();
      }
      finally{
        try{
          buffer.close();
        }
        catch(Exception ex){
          ex.printStackTrace();
        }
      }
      return sb.toString();
    }
  }

  仍在此类下,定义下载文件并写入手机SD卡:

    public int downFile(String urlStr,String path,String filename){
      //urlStr网络下载地址,path:写入SD卡上的地址,filename下载文件名
      InputStream inputStream = null;
      try{
        //声明FileUtils对象
        FileUtils fileUtils = new FileUtils();
        if(fileUtils.isFileExist(filename,path)){
          return 1; //文件已经存在则返回1
        }
        else{
          //将下载文件存入inputStream流中
          inputStream = getInputStreamFromUrl(urlStr);
          //将下载的文件写入SD卡
          File resultFile = fileUtils.write2SDFromInput(path, filename, inputStream);
          if(resultFile == null){
            return -1; //写入失败则返回-1
          }
        }
      }
      catch(Exception e){
        e.printStackTrace();
        return -1;
      }
      finally{
        try{
          inputStream.close();
        }
        catch(Exception e){
          e.printStackTrace();
        }
      }
      return 0; //下载写入SD卡成功则返回0
    }
    public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
      url = new URL(urlStr);
      HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
      InputStream inputStream = urlConn.getInputStream();
      return inputStream;
    }

  将下载的inputStream写入SD卡中,定义类FileUtils:

    public class FileUtils {
      private String SDCardRoot;

      public FileUtils() {
        // 得到当前外部存储设备的目录
        SDCardRoot = Environment.getExternalStorageDirectory()
          .getAbsolutePath();
      }

      /**
       * 在SD卡上创建文件
       *
       * @throws IOException
      */
      public File createFileInSDCard(String fileName, String dir)
        throws IOException {
          File file = new File(SDCardRoot + dir + File.separator + fileName);
          file.createNewFile();
          return file;
      }

      /**
       * 在SD卡上创建目录
       *
       * @param dirName
      */
      public File createSDDir(String dir) {
        File dirFile = new File(SDCardRoot + dir + File.separator);
        dirFile.mkdirs();
        return dirFile;
      }

      /**
       * 判断SD卡上的文件夹是否存在
      */
      public boolean isFileExist(String fileName, String path) {
        File file = new File(SDCardRoot + path + File.separator + fileName);
        return file.exists();
      }

      /**
       * 将另一个InputStream里面的数据写入到SD中
      */
      public File write2SDFromInput(String path, String fileName,
        InputStream input) {
          File file = null;
          OutputStream output = null;
          try {
            createSDDir(path);
            file = createFileInSDCard(fileName, path);
            //文件写入流,就是将数据写入file文件
            output = new FileOutputStream(file);
            //定义buffer大小为4K,就是每读取4K的内容就像文件中写入一次
            byte buffer[] = new byte[1024 * 4];
            int temp;
            while ((temp = input.read(buffer)) != -1) {
            output.write(buffer, 0, temp);
            }
          output.flush(); //清空缓存
          } catch (Exception ex) {
            ex.printStackTrace();
          } finally {
            try {
              output.close(); //关闭写入流
            } catch (Exception ex) {
              ex.printStackTrace();
            }
          }
          return file;
      }
    }

posted @ 2015-08-08 22:20  best.lei  阅读(558)  评论(0编辑  收藏  举报