如何在Java中取消Files.copy()? [英] How to cancel Files.copy() in Java?
本文介绍了如何在Java中取消Files.copy()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Java NIO复制内容:
I'm using Java NIO to copy something:
Files.copy(source, target);
但我想让用户取消此功能(例如,如果文件太大而且是需要一段时间)。
But I want to give users the ability to cancel this (e.g. if the file is too big and it's taking a while).
我该怎么做?
推荐答案
使用选项 ExtendedCopyOption.INTERRUPTIBLE
。
注意:
这个类可能无法在所有环境中公开。
Note: This class may not be publicly available in all environments.
基本上,您调用 Files.copy(...)
在一个新的线程中,然后使用 Thread.interrupt()
中断该线程:
Basically, you call Files.copy(...)
in a new thread, and then interrupt that thread with Thread.interrupt()
:
Thread worker = new Thread() {
@Override
public void run() {
Files.copy(source, target, ExtendedCopyOption.INTERRUPTIBLE);
}
}
worker.start();
然后取消:
worker.interrupt();
请注意,这将引发 FileSystemException
。
这篇关于如何在Java中取消Files.copy()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文