writeString method

Future<File?> writeString({
  1. required String str,
  2. required String fileName,
  3. String? filePath,
  4. FileMode? fileMode,
})

写入数据

Implementation

Future<File?> writeString({required String str, required String fileName, String? filePath, FileMode? fileMode}) async {
  // create({bool recursive: false})创建文件
  // createSync({bool recursive: false}) 同步创建文件
  // 可选命名参数:recursive 默认false,
  // 若为true  则路径中有目录不存在时 会递归创建目录
  // 若为false 则路径中的目录不存在时 会报错
  File? file;
  if (Platform.isWindows) {
    file = await getLocalSupportFile(fileName: fileName, filePath: filePath);
  } else if (Platform.isAndroid) {
    final exFile = await getExternalStorageFile(fileName: fileName, filePath: filePath);
    if (exFile == null) {
      file = await getLocalTemporaryFile(fileName: fileName, filePath: filePath);
    } else {
      file = exFile;
    }
  } else {
    file = await getLocalDocumentFile(fileName: fileName, filePath: filePath);
  }

  if (file == null) {
    return null;
  }

  try {
    final fileExists = await file.exists();

    if (!fileExists) {
      await file.create(recursive: true);
    }

    //以字符串方式写入
    return await file.writeAsString(str,
        flush: true,
        // 如果flush设置为`true` 则写入的数据将在返回之前刷新到文件系统
        mode: fileMode ?? FileMode.append,
        // 写入的模式 append(追加写入) read(只读) write(读写) writeOnly(只写)  writeOnlyAppend(只追加)
        encoding: utf8); // 设置编码
  } catch (e) {
    logger.e(tag: TAG, e.toString());
    return null;
  }
}