Android 普通文件下載

  /**
   * 下載文件
   */
  private void writeFile(Response response) {
        InputStream is = null;
        FileOutputStream fos = null;
        is = response.body().byteStream();
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(path, fileName);
        try {
            fos = new FileOutputStream(file);
            byte[] bytes = new byte[2048];
            int len = 0;
            long totalSize = response.body().contentLength();
            long sum = 0;
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes);
                sum += len;
                int press = (int) ((sum * 1.0f / totalSize) * 100);
                Message msg = handler.obtainMessage(1);
                msg.arg1 = press;
                handler.sendMessage(msg);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 設置進度
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                int mpress = msg.arg1;
                Log.i("----------進度:", String.valueOf(mpress));
                progress.setProgress(mpress);
            }
        }
    };

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章