简体   繁体   中英

Async Commons-io operations?

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.

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?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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