// 下载媒体文件
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();
}
}
}
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();
}
}
}