📄 downloader.java
字号:
package org.serain.shmily.downloadMusic;
import java.io.*;
import java.net.*;
import org.serain.shmily.vo.DownloadTask;
public class Downloader extends Thread{
private DownloadTask task;
private String url;
private String savePath;
private String fileName;
private boolean loading=true;
public Downloader(DownloadTask task,String savePath){
this.task=task;
this.savePath=savePath;
this.url=task.getMusicUrl();
String[] s=url.split("/");
this.fileName=s[s.length-1];
}
public void finish(){
task.setState("finish");
}
public void pause(){
task.setState("pause");
}
public void goon(){
task.setState("download");
}
public void run(){
try{
URL u=new URL(url);
task.setTotalBytes(u.openConnection().getContentLength());
task.setTimeRemain(task.getTotalBytes()/20000+"秒");
InputStream is=u.openStream();
BufferedInputStream bis=new BufferedInputStream(is);
FileOutputStream fos=new FileOutputStream(savePath+fileName);
BufferedOutputStream bos=new BufferedOutputStream(fos);
byte[] buffer=new byte[1024 * 10];
int len;
int timeTake=0;
//int flag=0;
int finishBytes=0;
while(!(task.getState().equals("finish"))){
if(task.getState().equals("pause")){
sleep(10000);//暂停时候睡眠10秒,防止无限循环占用系统资源
}else if(task.getState().equals("download")){
long start=System.currentTimeMillis();
if((len=bis.read(buffer))==-1){
task.setState("finish");
break;
}
bos.write(buffer,0,len);
long end = System.currentTimeMillis();
long time=end-start;
timeTake =timeTake+(int)time;
finishBytes+=len;
task.setFinishBytes(finishBytes);
//if(flag%20==0){//每20次设置一次
//设置进度
float proess=(float)finishBytes/(float)task.getTotalBytes();
task.setProess((int)(proess*100)+"%");
task.setTimeTake(timeTake/1000 + "秒");
if(time!=0){
//设置即时速度
int speed=len/(int)time;
task.setSpeed(speed+"kb/秒");
//设置剩余时间
int timeRemain;
if(speed!=0){
timeRemain=(task.getTotalBytes()-task.getFinishBytes())/speed;
task.setTimeRemain(timeRemain/1000 +"秒");
}
}
// System.out.println(fileName+"finishbytes:"+task.getFinishBytes()+" proess:"+task.getProess()+" speed: "+task.getSpeed()+" timeTake:"+task.getTimeTake()+" timeremain:"+task.getTimeRemain());
//}
//flag+=1;
}
}
is.close();
fos.close();
}catch(Exception e){
e.printStackTrace();
try {
throw new Exception("下载出现错误");
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public void setTaskState(String state){
task.setState(state);
}
public String getTaskState(){
return task.getState();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -