我正在使用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");
}
}
}
FileChannel
(https://dev59.com/guk5XIcBkEYKwwoY_O-N#42183069)。 - spongebob