利用HttpURLConnection下載檔案的核心程式碼程式碼
private void downLoad(String urlStr){
// 建立HashMap,儲存下載到的檔案資訊
Map map = new HashMap<String, Object>();
InputStream is = null;
FileOutputStream fos = null;
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
int len = conn.getContentLength(); // 記錄所要下載內容的總位元組數
map.put("length", len);
is = conn.getInputStream();
// 建立一個檔案物件,檔案將被建立到sdcard根目錄,檔名為下載開始時間的毫秒數+檔案字尾名
DataInputStream dis = new DataInputStream(is);
fos = new FileOutputStream("/mnt/sdcard/"+System.currentTimeMillis()+"."+urlStr.substring(urlStr.lastIndexOf(".")+1));
byte[] buffer = new byte[1024*10]; // 緩衝位元組陣列
int actualLen = 0;
while((actualLen=is.read(buffer)) != -1){
fos.write(buffer, 0, actualLen);
currentProgress += actualLen;
map.put("currentProgress", currentProgress);
mHandler.obtainMessage(1, map).sendToTarget();
fos.flush();
}
mHandler.obtainMessage(2).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos != null){
fos.close();
}
if(is != null){
is.close();
}
if(conn != null){
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}