Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

從 URL 下載原始資料並轉為 byte 陣列的方法

編輯:關於 Android 開發

從 URL 下載原始資料並轉為 byte 陣列的方法

在網路程式中,經常需要從指定的 URL 下載原始資料並以 byte 陣列的形式處理。以下提供一個靜態方法,透過 HttpURLConnection 讀取串流,並利用緩衝區逐步寫入 ByteArrayOutputStream,最終回傳 byte 陣列:

 1 public static byte[] loadRawDataFromURL(String u) throws Exception { 2 URL url = new URL(u); 3 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 4 5 InputStream is = conn.getInputStream(); 6 BufferedInputStream bis = new BufferedInputStream(is); 7 8 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 9 //緩存2KB 10 final int BUFFER_SIZE = 2*1024; 11 final int EOF = -1; 12 13 int c; 14 byte[] buf = new byte[BUFFER_SIZE]; 15 16 while (true) { 17 c = bis.read(buf); 18 if (c == EOF) 19 break; 20 21 baos.write(buf, 0, c); 22 } 23 24 conn.disconnect(); 25 is.close(); 26 27 byte[] data = baos.toByteArray(); 28 baos.flush(); 29 30 return data; 31 }

此方法以 2KB 為緩衝區大小,透過迴圈持續讀取資料直到串流結束(EOF),適合處理圖片、檔案等二進位資源的下載。取得 byte 陣列後,即可進一步用於 BitmapFactory 解碼或其他資料處理流程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved