鸿蒙Next ArkTS存储数据的工具类实现方法
在鸿蒙Next中使用ArkTS开发时,如何高效实现一个存储数据的工具类?希望能提供具体的实现方法,包括本地存储、数据加密和性能优化等方面的建议。
2 回复
在鸿蒙Next(HarmonyOS NEXT)中,使用ArkTS实现数据存储的工具类,主要通过@ohos.data.preferences(轻量级偏好数据库)或@ohos.data.relationalStore(关系型数据库)实现。以下是基于Preferences的轻量级键值对存储工具类示例:
import preferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
export class StorageUtil {
private static instance: StorageUtil | null = null;
private preferences: preferences.Preferences | null = null;
// 单例模式
public static getInstance(): StorageUtil {
if (!StorageUtil.instance) {
StorageUtil.instance = new StorageUtil();
}
return StorageUtil.instance;
}
// 初始化Preferences(异步)
async init(context: Context, name: string): Promise<void> {
try {
this.preferences = await preferences.getPreferences(context, name);
console.info('StorageUtil: Preferences initialized');
} catch (err) {
const error = err as BusinessError;
console.error(`StorageUtil: Initialization failed, code: ${error.code}, message: ${error.message}`);
}
}
// 存储字符串
async putString(key: string, value: string): Promise<void> {
if (!this.preferences) {
console.error('StorageUtil: Preferences not initialized');
return;
}
try {
await this.preferences.put(key, value);
await this.preferences.flush();
} catch (err) {
const error = err as BusinessError;
console.error(`StorageUtil: Put string failed, code: ${error.code}, message: ${error.message}`);
}
}
// 读取字符串
async getString(key: string, defaultValue: string = ''): Promise<string> {
if (!this.preferences) {
console.error('StorageUtil: Preferences not initialized');
return defaultValue;
}
try {
return await this.preferences.get(key, defaultValue);
} catch (err) {
const error = err as BusinessError;
console.error(`StorageUtil: Get string failed, code: ${error.code}, message: ${error.message}`);
return defaultValue;
}
}
// 删除数据
async delete(key: string): Promise<void> {
if (!this.preferences) {
console.error('StorageUtil: Preferences not initialized');
return;
}
try {
await this.preferences.delete(key);
await this.preferences.flush();
} catch (err) {
const error = err as BusinessError;
console.error(`StorageUtil: Delete failed, code: ${error.code}, message: ${error.message}`);
}
}
// 清空所有数据
async clear(): Promise<void> {
if (!this.preferences) {
console.error('StorageUtil: Preferences not initialized');
return;
}
try {
await this.preferences.clear();
await this.preferences.flush();
} catch (err) {
const error = err as BusinessError;
console.error(`StorageUtil: Clear failed, code: ${error.code}, message: ${error.message}`);
}
}
}
使用示例:
// 在EntryAbility中初始化
import { UIAbility } from '@kit.AbilityKit';
import { StorageUtil } from '../utils/StorageUtil';
export default class EntryAbility extends UIAbility {
async onCreate(): Promise<void> {
const storage = StorageUtil.getInstance();
await storage.init(this.context, 'myAppStorage');
}
}
// 在页面中使用
const storage = StorageUtil.getInstance();
await storage.putString('username', '张三');
const name = await storage.getString('username');
关键说明:
- 单例模式:确保全局唯一实例。
- 异步操作:所有存储方法均为异步,需使用
await。 - 错误处理:捕获
BusinessError并输出日志。 - 数据持久化:
flush()方法确保数据写入磁盘。 - 适用场景:适合配置信息、用户偏好等轻量数据。
对于复杂数据结构,建议使用relationalStore(关系型数据库)或序列化为JSON字符串存储。


