欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android 將文件下載到指定目錄的實(shí)現(xiàn)代碼

 更新時(shí)間:2017年06月23日 14:14:41   作者:走著學(xué)磔  
本文通過實(shí)例代碼給大家介紹了android將文件下載到指定目錄的實(shí)現(xiàn)方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的的朋友參考下吧

廢話不多說了額,直接給大家貼代碼了,具體代碼如下所示:

/**
   * 下載指定路徑的文件,并寫入到指定的位置
   *
   * @param dirName
   * @param fileName
   * @param urlStr
   * @return 返回0表示下載成功,返回1表示下載出錯(cuò)
   */
  public int downloadFile(String dirName, String fileName, String urlStr) {
    OutputStream output = null;
    try {
      //將字符串形式的path,轉(zhuǎn)換成一個(gè)url
      URL url = new URL(urlStr);
      //得到url之后,將要開始連接網(wǎng)絡(luò),以為是連接網(wǎng)絡(luò)的具體代碼
      //首先,實(shí)例化一個(gè)HTTP連接對象conn
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      //定義請求方式為GET,其中GET的大小寫不要搞錯(cuò)了。
      conn.setRequestMethod("GET");
      //定義請求時(shí)間,在ANDROID中最好是不好超過10秒。否則將被系統(tǒng)回收。
      conn.setConnectTimeout(6 * 1000);
      //請求成功之后,服務(wù)器會返回一個(gè)響應(yīng)碼。如果是GET方式請求,服務(wù)器返回的響應(yīng)碼是200,post請求服務(wù)器返回的響應(yīng)碼是206(貌似)。
      if (conn.getResponseCode() == 200) {
        //返回碼為真
        //從服務(wù)器傳遞過來數(shù)據(jù),是一個(gè)輸入的動作。定義一個(gè)輸入流,獲取從服務(wù)器返回的數(shù)據(jù)
        InputStream input = conn.getInputStream();
        File file = createFile(dirName + fileName);
        output = new FileOutputStream(file);
        //讀取大文件
        byte[] buffer = new byte[1024];
        //記錄讀取內(nèi)容
        int n = input.read(buffer);
          //寫入文件
          output.write(buffer, 0, n);
          n = input.read(buffer);
        }
        output.flush();
         input.close();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        output.close();
        System.out.println("success");
        return 0;
      } catch (IOException e) {
        System.out.println("fail");
        e.printStackTrace();
      }
    }
    return 1;
  }
  /**
   * 在SD卡的指定目錄上創(chuàng)建文件
   *
   * @param fileName
   */
  public File createFile(String fileName) {
    File file = new File(fileName);
    try {
      file.createNewFile();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return file;
  }

以上所述是小編給大家介紹的Android 將文件下載到指定目錄的實(shí)現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論