![](/img/trans.png)
[英]How to cancel Files.copy() in Java while not using a non api class?
[英]How to cancel Files.copy() in Java?
我正在使用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");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.