Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel Files.copy() in Java?

Tags:

java

io

nio

I'm using Java NIO to copy something:

Files.copy(source, target);

But I want to give users the ability to cancel this (e.g. if the file is too big and it's taking a while).

How should I do this?

like image 755
roim Avatar asked Jun 13 '13 09:06

roim


People also ask

What is Files copy in Java?

file. Files Class is used to copy bytes from a file to I/O streams or from I/O streams to a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. Methods: Based on the type of arguments passed, the Files class provides 3 types of copy() method.

How do I copy and paste a file in Java?

Another common way to copy a file with Java is by using the commons-io library. The latest version can be downloaded from Maven Central. Then, to copy a file we just need to use the copyFile() method defined in the FileUtils class. The method takes a source and a target file.

How do I move a file in Java?

You can move a file or directory by using the move(Path, Path, CopyOption...) method. The move fails if the target file exists, unless the REPLACE_EXISTING option is specified. Empty directories can be moved.

Which StandardCopyOption and LinkOption works with existing file or directory?

The following StandardCopyOption and LinkOption enums are supported: REPLACE_EXISTING – Performs the copy even when the target file already exists.


2 Answers

Use the option ExtendedCopyOption.INTERRUPTIBLE.

Note: This class may not be publicly available in all environments.

Basically, you call Files.copy(...) in a new thread, and then interrupt that thread with Thread.interrupt():

Thread worker = new Thread() {
    @Override
    public void run() {
        Files.copy(source, target, ExtendedCopyOption.INTERRUPTIBLE);
    }
}
worker.start();

and then to cancel:

worker.interrupt();

Notice that this will raise a FileSystemException.

like image 155
roim Avatar answered Oct 18 '22 22:10

roim


For Java 8 (and any java without ExtendedCopyOption.INTERRUPTIBLE), this will do the trick:

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");
        }
    }
}
like image 44
Mark Jeronimus Avatar answered Oct 18 '22 21:10

Mark Jeronimus