简体   繁体   English

异步Commons-io操作?

[英]Async Commons-io operations?

I want to download a file from URL and I'm using commons-io for that. 我想从URL下载文件,我正在使用commons-io 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. 基本上,如果无法在指定时间内下载文件,则该方法应返回错误。

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

you could do something like this. 你可以做这样的事情。

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
}

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. 如果它没有及时完成,你可以尝试取消该任务并中断它,虽然中断线程可能不会工作,因为我不认为FileUtils.copyURLToFile()检查线程的中断标志。 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. 如果你真的想要停止下载,你必须自己实现copyURLToFile并定期检查Thread.interrupted()以便在线程被中断时停止下载。

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

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