Tinus Tate
Tinus Tate

Reputation: 2365

How to cancel Files.copy() in Java while not using a non api class?

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

Upvotes: 2

Views: 308

Answers (1)

VGR
VGR

Reputation: 44355

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.

Upvotes: 3

Related Questions