【问题标题】:How to cancel Files.copy() in Java?如何在 Java 中取消 Files.copy()?
【发布时间】:2013-06-09 15:37:57
【问题描述】:

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

Files.copy(source, target);

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

我应该怎么做?

【问题讨论】:

    标签: java io nio


    【解决方案1】:

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

    【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-06-22
      • 2014-05-21
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 2021-12-16
      • 2011-02-19
      • 2021-06-13
      • 1970-01-01
      相关资源
      最近更新 更多