java 异步文件下载_在Java中并行或异步下载多个文件

本文提供了一个修复后的Java代码示例,用于并行或异步下载多个文件,利用ExecutorService实现。通过Callable和Future,每个文件下载任务在单独的线程中执行,提高效率。同时,介绍了代码中对错误处理和状态跟踪的改进。
摘要由CSDN通过智能技术生成

实际上,经过仔细研究,鲍里斯的代码是错误的,有时确实不会设置一些东西.这是一个更好的版本,修复了:

public List download(List attachments) {

ExecutorService executorService = Executors.newCachedThreadPool();

List> futures = new ArrayList>();

for (final Attachment attachment : attachments) {

futures.add(executorService.submit(new Callable() {

@Override

public Attachment call() throws Exception {

return doDownload(attachment);

}

}));

}

for (Future future: futures) {

try {

future.get();

} catch (Exception ex) {

// Do something

}

}

return attachments;

}

private Attachment doDownload(Attachment attachment) throws Exception {

attachment.setDownStatus("Failed");

attachment.setDestLocation("C:\\Users\\attachments");

String attUrl = attachment.getUrl();

String fileName = attachment.getFileName();

URL url = new URL(attUrl);

File fileLocation = new File(attachment.getDestLocation(), fileName);

FileUtils.copyURLToFile(url, fileLocation);

if (fileLocation.exists()) {

attachment.setDownStatus("Completed");

}

return attachment;

}

但是,鉴于您的附件结构以及如何使用它,这绝对不是最佳选择.我没有解决这个问题:我只回答了问题.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值