我正在使用Java NIO复制一些内容:
Files.copy(source, target);
但我想让用户取消此功能(例如,如果文件太大而且需要一段时间)。
我该怎么做?
答案 0 :(得分:28)
使用选项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 :(得分:0)
对于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");
}
}
}