
回复
在鸿蒙应用开发中,数据持久化是必不可少的。本文通过实战案例,全面讲解如何在 HarmonyOS 中使用本地存储和文件操作,助你掌握数据保存的核心技能!
存储类型 | 适用场景 | 特点 |
---|---|---|
Preferences (轻量存储) |
保存少量配置信息,如用户设置、Token等 | 类似本地 key-value 存储 |
文件存储(FileIO) |
保存图片、文档、大体积数据 | 支持二进制流和文本操作 |
在 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();
}
在 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
模块。
简单示例:
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 + 数据交互》——带你做一个高颜值、可切换月份的鸿蒙日历控件!