异步 Commons-io 操作?

bra*_*ram 0 java io apache-commons

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

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

Pie*_*ter 5

你可以做这样的事情。

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
}
Run Code Online (Sandbox Code Playgroud)

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