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

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

Files.copy(source, target); 

但是我想让用户能够取消它(例如,如果文件太大而且需要一段时间)。

我该怎么做?

使用选项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

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