繁体   English   中英

异步Commons-io操作?

[英]Async Commons-io operations?

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

我查看了javadocs并发现所有IO操作都是同步的(阻止IO操作)是否有任何其他替代库提供与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()以便在线程被中断时停止下载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM