如何在Java中取消Files.copy()操作?

15

我正在使用Java NIO复制一些东西:

Files.copy(source, target);

但我希望给用户提供取消上传的功能(例如,如果文件太大且上传时间过长)。

我应该如何做到这一点?

2个回答

30

使用选项ExtendedCopyOption.INTERRUPTIBLE

注意:此类可能在某些环境中不是公开可用的。

基本上,您在新线程中调用Files.copy(...),然后使用Thread.interrupt()中断该线程:

Thread worker = new Thread() {
    @Override
    public void run() {
        Files.copy(source, target, ExtendedCopyOption.INTERRUPTIBLE);
    }
}
worker.start();

然后进行取消操作:

worker.interrupt();

请注意,这将引发FileSystemException异常。


1
在Java SE 8中,Oracle JDK不支持此选项。作为替代方案,请考虑使用FileChannel(https://dev59.com/guk5XIcBkEYKwwoY_O-N#42183069)。 - spongebob

1

对于Java 8(以及没有ExtendedCopyOption.INTERRUPTIBLE的任何Java),这将解决问题:

public static void streamToFile(InputStream stream, Path file) throws IOException, InterruptedException {
    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(file))) {
        byte[] buffer = new byte[8192];
        while (true) {
            int len = stream.read(buffer);
            if (len == -1)
                break;

            out.write(buffer, 0, len);

            if (Thread.currentThread().isInterrupted())
                throw new InterruptedException("streamToFile canceled");
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接