1. 程式人生 > >網絡文件下載

網絡文件下載

mp4 數據 cto download tac ktr tor onf name

這是我自己寫的文件下載:

如果下載鏈接中有漢字,請先對漢字部分進行轉碼 在進行文件下載,註意在線程中下載文件,

單下載文件

/**
* 下載文件
*
* @param downloadURL 要下載的文件網絡路徑
*/
private void downloadFile(String downloadURL) {
FileOutputStream outputStream=null;
InputStream inputStream=null;
try {
if (downloadURL == null) {
Log.e("download", "脈盤下載文件的鏈接地址為空");
return;
}
//獲取SD卡的根目錄
String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
//你要把文件下載到那個文件夾,targetDir就這個文件夾的名稱
File rootFolder = new File(absolutePath + "/targetDir");
if (!rootFolder.exists()) {
rootFolder.mkdirs();
}
File folder = new File(absolutePath + "/targetDir");
if (!folder.exists()) {
folder.mkdirs();
}
//如果這個文件是MP4文件,後綴名suffix=.mp4
String suf = ".mp4";
//文件的名字
String fileName = "myVideo";
String saveFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/targetDir" + fileName + suf;

URL url = new URL(downloadURL);
//打開連接
URLConnection conn = url.openConnection();
//打開輸入流
inputStream = conn.getInputStream();
//獲得長度
final int contentLength = conn.getContentLength();
//先在本地看下這個文件存不存在,
File destinationFile = new File(saveFileName);
if (destinationFile.exists()) {
//如果存在就把他刪了,避免下載的文件和原來已有的文件重復了
destinationFile.delete();
}
//創建字節流
byte[] bs = new byte[1024];
int len;
outputStream = new FileOutputStream(destinationFile);
int mSize = 0;
//寫數據
while ((len = inputStream.read(bs)) != -1) {
//已下載數據大小
mSize += len;
outputStream.write(bs, 0, len);
}
//下載完成
Log.e("download","下載完成,文件保存在:"+saveFileName+"這個路徑");
} catch (IOException e) {
//如果下載失敗了,就會打印日誌
Log.e("download","下載文件異常msg:" + e.getMessage());
e.printStackTrace();
} finally {
//不管有沒有下載成功都要把流關掉
if (outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

網絡文件下載