writeToFile method

bool writeToFile(
  1. String filePath
)

将文本内容写入指定文件目录中

filePath 文件路径

返回结果: 写入成功返回true,写入失败返回false。

示例:

bool result = 'hello world'.writeToFile('/tmp/test.txt');
print(result); // true 或 false

Implementation

bool writeToFile(String filePath) {
  try {
    final file = File(filePath);
    // 确保目录存在
    file.parent.createSync(recursive: true);
    // 写入字符串内容
    file.writeAsStringSync(this);
    return true;
  } catch (e) {
    Logger.log('Error writing to file: $e');
    return false;
  }
}