2

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() ?

Community
  • 1
  • 1
Tinus Tate
  • 2,237
  • 2
  • 12
  • 33

1 Answers1

3

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.

VGR
  • 40,506
  • 4
  • 48
  • 63