Search code examples
javaiorandomaccessfile

how can i cancel file creation process in java in my example?


I’m creating an empty file with specified size as below.

final long size = 10000000000L;
final File file = new File("d://file.mp4");

Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.setLength(size);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});
t.start();

For big sizes like 5GB or less and more, this process takes more time on android devices. Now my question is how can I cancel the creating file process Whenever i wanted? thanks.


Solution

  • raf.setLength calls seek under the hood, which is a native function, so it's not clear if the operation is actually cancellable through an interrupt or by other means.

    Can you chunk the creation of the file yourself, something like:

    final long size = 10000000000L;
    final File file = new File("d://file.mp4");
    volatile boolean cancelled = false;
    
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            long bytesRemaining = size;
            long currentSize = 0;
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            try {
                while ( bytesRemaining > 0 && !cancelled ) {
                    // !!!THIS IS NOT EXACTLY CORRECT SINCE
                    // YOU WILL NEED TO HANDLE EDGE CONDITIONS
                    // AS YOU GET TO THE END OF THE FILE.
                    // IT IS MEANT AS AN ILLUSTRATION ONLY!!!
                    currentSize += CHUNK_SIZE; // you decide how big chunk size is
                    raf.setLength(currentSize);
                    bytesRemaining -= CHUNK_SIZE 
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
    
    // some other thread could cancel the writing by setting the cancelled flag
    

    Disclaimer: I don't know what kind of performance this will have at the size files you are creating. It will likely have some overhead for each call to seek. Try it out, and see what performance looks like.