
前言fileIo是 HarmonyOS 提供的文件系统操作 API支持文件的创建、读写、删除等操作。在需要自定义配置文件的场景中fileIo JSON 序列化是一种灵活的存储方案。本文以「猫猫大作战」的配置文件读写为锚点讲解 fileIo 的文本文件操作。提示本系列不讲 ArkTS 基础语法与环境搭建假设你已跟完第 1–140 篇。本篇是阶段四第 141 篇。一、fileIo 文件读写1.1 写入文件import { fileIo } from kit.CoreFileKit; import { common } from kit.AbilityKit; import { json } from kit.ArkTS; async function saveConfigT(key: string, data: T) { const context getContext() as common.UIAbilityContext; const filePath context.filesDir / key .json; const file fileIo.openSync(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY); fileIo.writeSync(file.fd, JSON.stringify(data)); fileIo.closeSync(file); }1.2 读取文件async function loadConfigT(key: string, defaultVal: T): PromiseT { try { const context getContext() as common.UIAbilityContext; const filePath context.filesDir / key .json; const file fileIo.openSync(filePath, fileIo.OpenMode.READ_ONLY); const content fileIo.readSync(file.fd); fileIo.closeSync(file); return JSON.parse(content) as T; } catch { return defaultVal; } }二、总结fileIo 实现文件的读写操作配合 JSON.serialize/parse 实现结构化数据持久化。核心要点openSync/readSync/writeSync/closeSync同步文件操作路径使用context.filesDirJSON.stringify/parse序列化/反序列化下一篇预告第 142 篇将深入 sandbox 路径——filesDir/cacheDir 的选用。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源fileIo API 参考开源鸿蒙跨平台社区第 140 篇AppStorage第 142 篇sandbox 路径