如何在不使用非api类的情况下取消Java中的Files.copy()? [英] How to cancel Files.copy() in Java while not using a non api class?

查看:119
本文介绍了如何在不使用非api类的情况下取消Java中的Files.copy()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Files.copy 方法下载文件:

  Files.copy(in,Paths.get(targetZipFile),StandardCopyOption.REPLACE_EXISTING)

如果下载很慢我想取消它。



我在stackoverflow上找到了以下与标题相同的主题:
如何在Java中取消Files.copy()?



但此解决方案使用私有api :



访问限制:类型'ExtendedCopyOption'不是API(限制于必需的库' C:\Program Files \ Java @\\\\\
$ b

有没有其他方法可以取消 Files.copy()

解决方案

如果你想坚持使用NIO,你可以使用:

  try(FileChannel zip = FileChannel.open(Paths.get(targetZipFile),
StandardOpenOption.CREATE,StandardOpenOption.WRITE)){

zip.transferFrom(Channels.newChannel(in),0,Long.MAX_VALUE) ;
}

根据 documentation ,FileChannel.transferFrom如果线程被中断,将抛出ClosedByInterruptException。


I'm downloading an file with Files.copy method:

Files.copy(in, Paths.get(targetZipFile), StandardCopyOption.REPLACE_EXISTING)

If the download is slow i wish to cancel it.

I found the following topic on stackoverflow with the same title: How to cancel Files.copy() in Java?

But this solution uses a private api:

Access restriction: The type 'ExtendedCopyOption' is not API (restriction on required library 'C:\Program Files\Java\jdk1.8.0_60\jre\lib\rt.jar')

Is there another way to cancel Files.copy() ?

解决方案

If you wish to stick with NIO, you can use:

try (FileChannel zip = FileChannel.open(Paths.get(targetZipFile),
    StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {

    zip.transferFrom(Channels.newChannel(in), 0, Long.MAX_VALUE);
}

As per the documentation, FileChannel.transferFrom will throw a ClosedByInterruptException if the thread is interrupted.

这篇关于如何在不使用非api类的情况下取消Java中的Files.copy()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆