初始化LoadSomething开始准备
初始化DownloadTask对象
调用LoadSomething的对象调用DownloadTask对象进行计时运行
LoadSomething load = new LoadSomething();
DownloadTask downloadTask = new DownloadTask(URL, getDir());
// 开始下载,并设定超时限额为3毫秒
load.beginToLoad(downloadTask, 60000, TimeUnit.MILLISECONDS);
2. LoadSomething对象代码
importjava.io.FileNotFoundException;
import java.io.IOException;
importjava.util.concurrent.ExecutionException;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
importjava.util.concurrent.Future;
importjava.util.concurrent.TimeUnit;
importjava.util.concurrent.TimeoutException;
public class LoadSomething {
// 线程池服务接口
private ExecutorService executor;
public LoadSomething() {
executor = Executors.newSingleThreadExecutor();
}
public voidbeginToLoad(DownloadTask task, long timeout,
TimeUnit timeType) {
Future<?> future = executor.submit(task);
try {
future.get(timeout, timeType);
task.throwException();
} catch (InterruptedException e) {
System.out.println("下载任务已经取消");
} catch (ExecutionException e) {
System.out.println("下载中发生错误,请重新下载");
} catch (TimeoutException e) {
System.out.println("下载超时,请更换下载点");
} catch (FileNotFoundException e) {
System.out.println("请求资源找不到");
} catch (IOException e) {
System.out.println("数据流出错");
} finally {
task.setStop(true);
// 因为这里的下载测试不用得到返回结果,取消任务不会影响结果
future.cancel(true);
}
}
}
DownloadTask代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import org.apache.commons.io.FileUtils;
class DownloadTask implements Runnable {
private String url;
private String dir;
// 接收在run方法中捕获的异常,然后自定义方法抛出异常
private Throwable exception;
//是否关闭此下载任务
private boolean isStop = false;
public void setStop(boolean isStop) {
this.isStop = isStop;
}
public DownloadTask(String url, String dir) {
this.url = url;
this.dir = dir;
}
/**
* 下载大数据
*
* @param filename
* @throws FileNotFoundException
* , IOException
*/
private void download() throws FileNotFoundException,IOException {
try {
URL httpurl = new URL(url);
String fileName = getFileNameFromUrl(url);
System.out.println(fileName);
File f = new File(dir + "/" + fileName);
FileUtils.copyURLToFile(httpurl, f);
} catch (Exception e) {
e.printStackTrace();
}
}
public static StringgetFileNameFromUrl(String url) {
String name = new Long(System.currentTimeMillis()).toString()+ ".X";
int index = url.lastIndexOf("/");
if (index > 0) {
name = url.substring(index + 1);
if (name.trim().length() > 0){
return name;
}
}
return name;
}
public void throwException() throws FileNotFoundException,IOException {
if (exception instanceof FileNotFoundException)
throw (FileNotFoundException)exception;
if (exception instanceof IOException)
throw (IOException) exception;
}
@Override
public void run() {
try {
download();
} catch (FileNotFoundException e) {
exception = e;
} catch (IOException e) {
exception = e;
}
}
}
3.