【发布时间】:2013-06-09 15:37:57
【问题描述】:
我正在使用 Java NIO 复制一些东西:
Files.copy(source, target);
但我想让用户能够取消此操作(例如,如果文件太大并且需要一段时间)。
我应该怎么做?
【问题讨论】:
我正在使用 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。
【讨论】:
FileChannel。
对于 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");
}
}
}
【讨论】: