How to cancel Files.copy() in Java?

前端 未结 2 1791
-上瘾入骨i
-上瘾入骨i 2021-01-08 01:22

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

2条回答
  •  执笔经年
    2021-01-08 02:11

    Use the option ExtendedCopyOption.INTERRUPTIBLE.

    Note: This class may not be publicly available in all environments.

    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();
    

    and then to cancel:

    worker.interrupt();
    

    Notice that this will raise a FileSystemException.

提交回复
热议问题