在我的示例中,如何在Java中取消文件创建过程



我正在创建一个带有指定大小的空文件。

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

对于5GB或以下尺寸之类的大尺寸,此过程在Android设备上需要更多时间。现在我的问题是如何在需要时取消创建文件过程?谢谢。

raf.setLength在引擎盖下调用 seek,这是本机函数,因此尚不清楚该操作是否可以通过中断或其他方式来取消操作。

您可以自己创建文件的创建,例如:

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

免责声明:我不知道您正在创建的大小文件会具有什么样的性能。每个呼吁寻求的电话可能会有一些开销。尝试一下,看看性能是什么样的。

最新更新