异步Commons-io操作? [英] Async Commons-io operations?

查看:125
本文介绍了异步Commons-io操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从URL下载文件,并且正在使用 commons-io .在下载时,我想根据要下载的文件类型设置超时时间.基本上,如果无法在指定时间内下载文件,则该方法应返回错误.

I want to download a file from URL and I'm using commons-io for that. While I'm downloading I want to set timeout based on the type of file I want to download. Basically, the method should return with error, if it could not download the file within the specified time.

我查看了 javadocs 并发现所有IO操作都是同步的(阻止IO操作) 是否还有其他替代库提供与commons-io相同的效率和易用性?

I looked at javadocs and found all IO operations are synchronous( blocking IO operations) Is there any other alternative libraries which offer same efficiency and ease-of-use as same as commons-io?

推荐答案

您可以执行以下操作.

ExecutorService executorService = acquireExecutorService();

final int readTimeout = 1000;
final int connectionTimeout = 2000;
final File target = new File("target");
final URL source = new URL("source");

Future<?> task = executorService.submit(new Runnable() {
    @Override
    public void run() {
        try {
            FileUtils.copyURLToFile(source, target, connectionTimeout, readTimeout);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
});
try {
    task.get(30, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException e) {
    //handle exceptions
} catch (TimeoutException e) {
    task.cancel(true); //interrupt task
}

通过使用执行程序服务,您可以异步下载文件. task.get(30, TimeUnit.SECONDS);指定要等待下载完成的时间.如果没有及时完成,您可以尝试取消任务并中断它,尽管中断线程可能无法正常工作,因为我不认为FileUtils.copyURLToFile()检查线程的中断标志.这意味着下载仍将在后台继续.如果您确实要停止下载,则必须自己实施copyURLToFile并定期检查Thread.interrupted(),以便在线程中断时停止下载.

By using an executor service you can download the file asynchronously. task.get(30, TimeUnit.SECONDS); specifies how long you want to wait for the download to complete. If it's not done in time, you could try to cancel the task and interrupt it, although interrupting the thread probably won't work as I don't think that FileUtils.copyURLToFile() checks the interrupted flag of the thread. This means that the download will still continue in the background. If you really want to stop the download, you'll have to implement copyURLToFile yourself and check Thread.interrupted() regularly in order to stop the download when the thread was interrupted.

这篇关于异步Commons-io操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆