Android從網路某個地址下載檔案、寫入SD卡

來源:互聯網
上載者:User

標籤:

   首先建立一個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;
      }
    }

Android從網路某個地址下載檔案、寫入SD卡

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.