Dart 快速读取文件 File.existsSync 偶尔返回false

如果 File.existsSync 有时候会返回 false,那可能是文件正在被另一个进程或线程写入。在 Dart 中,File.existsSync 方法是同步的,它会立刻返回结果。如果文件正在被写入,File.existsSync 可能会在文件被写入之前就返回 false。

为了解决这个问题,可以使用 File.statSync 方法来检查文件的信息,而不是直接使用 File.existsSync。例如:

import 'dart:io';

void main() {
  var file = File('some_file.txt');

  // Use File.statSync to check the file's information.
  var fileStat = file.statSync();

  // Check if the file exists by checking the "type" property of the FileStat object.
  if (fileStat.type == FileSystemEntityType.notFound) {
    print('The file does not exist.');
  } else {
    print('The file exists and is not being written to by another process or thread.');
  }
}

使用 File.statSync 方法来检查文件的信息可以确保在文件被写入时也能正确处理。

另外,如果想要在文件被写入时仍然能正确处理,可以使用异步版本的文件方法,例如 File.exists 或 File.stat。这些方法会在文件被写入时等待,直到文件写入完成才返回结果。例如:

import 'dart:io';

void main() async {
  var file = File('some_file.txt');

  // Use the asynchronous File.stat method.
  var fileStat = await file.stat();

  // Check if the file exists by checking the "type" property of the FileStat object.
  if (fileStat.type == FileSystemEntityType.notFound) {
    print('The file does not exist.');
  } else {
    print
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容