class DownloadThread extends Thread{
FileInfo fileInfo;
public DownloadThread(FileInfo fileInfo) {
this.fileInfo = fileInfo;
}
@Override
public void run() {
//连接网络文件
HttpURLConnection conn = null;
RandomAccessFile rfa = null;
try {
URL url=new URL(fileInfo.getUrl());
conn= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
int length=-1;
if (conn.getResponseCode()==HttpStatus.SC_OK){
//获取文件长度
length=conn.getContentLength();
}
if (length<=0){
return;
}
//在本地创建文件
File dir=new File(DOWNLOAD_PATH);
if (!dir.exists()){
dir.mkdir();
}
File file=new File(dir,fileInfo.getFileName());
rfa=new RandomAccessFile(file,"rwd");
//设置文件长度
rfa.setLength(length);
fileInfo.setLength(length);
handler.obtainMessage(MSG_INIT,fileInfo).sendToTarget();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
conn.disconnect();
rfa.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件下载线程代码备注
最新推荐文章于 2024-10-03 08:55:44 发布