在我的示例中,如何取消 java 中的文件创建过程?
how can i cancel file creation process in java in my example?
我正在创建一个指定大小的空文件,如下所示。
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
免责声明:我不知道在您创建的文件大小下它会有什么样的性能。每次调用 seek 可能会有一些开销。尝试一下,看看性能如何。
我正在创建一个指定大小的空文件,如下所示。
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
免责声明:我不知道在您创建的文件大小下它会有什么样的性能。每次调用 seek 可能会有一些开销。尝试一下,看看性能如何。