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

如何在Java中取消Files.copy()?,java,io,nio,Java,Io,Nio,我正在使用Java NIO复制一些东西: Files.copy(source, target); 但我想让用户能够取消此操作(例如,如果文件太大,需要一段时间) 我应该怎么做?使用选项ExtendedCopyOption.interruptable 注意: 此类可能并非在所有环境中都公开可用 基本上,您可以调用文件。在新线程中复制(…),然后使用thread.interrupt()中断该线程: 然后取消: worker.interrupt(); 请注意,对于Java 8(以及任何不带Exte

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

Files.copy(source, target);
但我想让用户能够取消此操作(例如,如果文件太大,需要一段时间)


我应该怎么做?

使用选项
ExtendedCopyOption.interruptable

注意: 此类可能并非在所有环境中都公开可用

基本上,您可以调用
文件。在新线程中复制(…)
,然后使用
thread.interrupt()中断该线程:

然后取消:

worker.interrupt();
请注意,对于Java 8(以及任何不带ExtendedCopyOption.Interruptable的Java),这将引发
FileSystemException

,这将实现以下功能:

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");
        }
    }
}

在JavaSE8中,Oracle JDK不支持此选项。或者,考虑一下。
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");
        }
    }
}