1. 程式人生 > >Android URL 下載檔案

Android URL 下載檔案

 首先需要一個執行緒。
 new Thread(new Runnable() {
           @Override
           public void run() {
               try {
                   URL url = new URL(entity.getUrl());
                   //開啟連線
                   URLConnection conn = url.openConnection();
                   //開啟輸入流
                   InputStream is = conn.getInputStream();
                   //獲得長度
                   int contentLength = conn.getContentLength();
                   //建立資料夾 MyDownLoad,在儲存卡下
                   String dirName = context.getExternalFilesDir(null).getPath() + "/MyDownLoad/";
                   File file = new File(dirName);
                   //不存在建立
                   if (!file.exists()) {
                       file.mkdir();
                   }
                   //下載後的檔名
                   String fileName = dirName + entity.getTitle() +".mp3";
                   File file1 = new File(fileName);
                   if (file1.exists()) {
                       file1.delete();
                   }
                   //建立位元組流
                   byte[] bs = new byte[1024];
                   int len;
                   OutputStream os = new FileOutputStream(fileName);
                   //寫資料
                   while ((len = is.read(bs)) != -1) {
                       os.write(bs, 0, len);
                   }
                   //完成後關閉流
                   os.close();
                   is.close();
                   Log.e("run", "下載完成了~" + dirName );
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       }).start();