在鸿蒙应用开发中,数据持久化是必不可少的。本文通过实战案例,全面讲解如何在 HarmonyOS 中使用本地存储和文件操作,助你掌握数据保存的核心技能!
🧠 一、鸿蒙常用存储方式简介
| 存储类型 | 适用场景 | 特点 |
|---|---|---|
Preferences (轻量存储) | 保存少量配置信息,如用户设置、Token等 | 类似本地 key-value 存储 |
文件存储(FileIO) | 保存图片、文档、大体积数据 | 支持二进制流和文本操作 |
📦 二、实战开发:记住我(保存登录状态)
需求:
- 用户第一次登录后,保存登录信息
- 下次打开自动读取并展示
- 支持清除登录信息
🛠️ 三、轻量存储(Preferences)使用指南
1. 封装 StorageService
在 model/StorageService.ets 文件中:
import preferences from '@ohos.data.preferences';
let prefs: preferences.Preferences;
async function getPreferences() {
if (!prefs) {
prefs = await preferences.getPreferences(globalThis.getContext(), 'user_info');
}
return prefs;
}
export async function saveLoginInfo(username: string) {
const store = await getPreferences();
await store.put('username', username);
await store.flush(); // 刷新保存
}
export async function getLoginInfo(): Promise<string> {
const store = await getPreferences();
return await store.get('username', '');
}
export async function clearLoginInfo() {
const store = await getPreferences();
await store.delete('username');
await store.flush();
}
2. 创建登录页
在 pages/LoginPage.ets:
import { saveLoginInfo, getLoginInfo, clearLoginInfo } from '../model/StorageService';
@Entry
@Component
struct LoginPage {
@State username: string = ''
@State savedUsername: string = ''
async aboutToAppear() {
this.savedUsername = await getLoginInfo();
}
build() {
Column() {
TextInput({ placeholder: '请输入用户名' })
.onChange(v => this.username = v)
.margin({ bottom: 20 })
Button('登录').onClick(async () => {
if (this.username) {
await saveLoginInfo(this.username);
this.savedUsername = this.username;
}
}).margin({ bottom: 20 })
Button('清除登录信息').onClick(async () => {
await clearLoginInfo();
this.savedUsername = '';
})
if (this.savedUsername) {
Text(`欢迎回来,${this.savedUsername}!`).fontSize(20).margin({ top: 30 })
}
}
.padding(20)
.alignItems(HorizontalAlign.Center)
}
}
📸 四、效果展示图
运行后的界面示例 👇
- 登录成功后,保存用户名
- 下次打开自动欢迎用户
- 支持一键清除登录信息
🗂️ 五、进阶:文件读写操作(FileIO)
如果需要保存复杂数据或文件,比如图片/大文本,可以使用 FileIO 模块。
简单示例:
import fileio from '@ohos.fileio';
async function writeFile(filePath: string, content: string) {
const fd = await fileio.open(filePath, fileio.OpenMode.CREATE | fileio.OpenMode.WRONLY);
await fileio.write(fd, content);
await fileio.close(fd);
}
async function readFile(filePath: string): Promise<string> {
const fd = await fileio.open(filePath, fileio.OpenMode.READ_ONLY);
const buffer = new ArrayBuffer(1024);
await fileio.read(fd, buffer);
await fileio.close(fd);
return String.fromCharCode.apply(null, new Uint8Array(buffer));
}
- 写文件:保存文本、日志、缓存内容。
- 读文件:读取本地文件内容,如离线数据处理。
💬 六、常见问题排查
| 问题 | 解决方案 |
|---|---|
| 无法保存数据 | 确认权限(例如读取/写入权限) |
| Preferences 报错 | 确保异步调用正确,使用 await |
| 文件路径异常 | 使用 getContext().filesDir 获取安全路径 |
📘 七、总结
通过本篇实操,你掌握了鸿蒙中的两种常用本地存储方式:
- ✅ 小数据用
Preferences - ✅ 大文件用
FileIO
掌握这两套能力,90%以上的应用存储需求你都能轻松搞定!
📖 下篇预告
《打造鸿蒙原生日历组件:自定义UI + 数据交互》——带你做一个高颜值、可切换月份的鸿蒙日历控件!