鸿蒙开发时,如何管理应用的本地存储,如保存和读取数据?

  1. 鸿蒙开发时,如何管理应用的本地存储,如保存和读取数据?
鸿蒙开发
7天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
yanftch

在鸿蒙(HarmonyOS)应用开发中,本地数据存储是核心功能之一。以下是鸿蒙管理本地存储的常用方法及详细实现步骤,涵盖轻量级数据、关系型数据库和文件存储等多种场景:


### 1. 轻量级数据存储:Preferences 适用于简单键值对(如用户配置、开关状态等)。

#### 1.1 初始化 Preferences 实例

import { BusinessError } from '@ohos.base';
import { preferences } from '@ohos.data.preferences';

// 定义存储文件名和模式
const PREFERENCES_NAME = 'myAppSettings';
const MODE = preferences.Preferences.MODE_PRIVATE;

// 获取 Preferences 实例
let pref: preferences.Preferences | null = null;
try {
  preferences.getPreferences(this.context, PREFERENCES_NAME, MODE)
    .then((result: preferences.Preferences) => {
      pref = result;
      console.log('Preferences initialized');
    }).catch((err: BusinessError) => {
      console.error(`Failed to init preferences: ${err.code}, ${err.message}`);
    });
} catch (err) {
  console.error(`Exception: ${err.code}, ${err.message}`);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

#### 1.2 写入数据

async function saveData(key: string, value: preferences.ValueType) {
  if (!pref) return;
  try {
    await pref.put(key, value);  // 支持 string | number | boolean
    await pref.flush();          // 确保数据持久化
    console.log('Data saved');
  } catch (err) {
    console.error(`Save failed: ${err.code}, ${err.message}`);
  }
}

// 示例:保存用户主题偏好
saveData('theme_mode', 'dark');
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

#### 1.3 读取数据

async function loadData(key: string, defaultValue: preferences.ValueType) {
  if (!pref) return defaultValue;
  try {
    const value = await pref.get(key, defaultValue);
    console.log(`Loaded data: ${value}`);
    return value;
  } catch (err) {
    console.error(`Load failed: ${err.code}, ${err.message}`);
    return defaultValue;
  }
}

// 示例:读取主题设置
const theme = await loadData('theme_mode', 'light');
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

### 2. 关系型数据库:RDB Store 适用于结构化数据(如用户列表、订单记录等)。

#### 2.1 定义数据库结构

import { relationalStore } from '@ohos.data.relationalStore';

// 定义表结构
const SQL_CREATE_TABLE = `
  CREATE TABLE IF NOT EXISTS user (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    age INTEGER,
    email TEXT UNIQUE
  )`;

// 配置数据库参数
const config: relationalStore.StoreConfig = {
  name: 'myAppDB',  // 数据库名
  securityLevel: relationalStore.SecurityLevel.S1  // 安全级别
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

#### 2.2 初始化数据库

let rdbStore: relationalStore.RdbStore | null = null;

async function initRDB() {
  try {
    rdbStore = await relationalStore.getRdbStore(this.context, config);
    await rdbStore.executeSql(SQL_CREATE_TABLE);
    console.log('RDB initialized');
  } catch (err) {
    console.error(`RDB init failed: ${err.code}, ${err.message}`);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

#### 2.3 插入数据

async function insertUser(user: { name: string, age: number, email: string }) {
  if (!rdbStore) return;
  const valueBucket: relationalStore.ValuesBucket = {
    'name': user.name,
    'age': user.age,
    'email': user.email
  };
  try {
    const rowId = await rdbStore.insert('user', valueBucket);
    console.log(`Inserted row ID: ${rowId}`);
  } catch (err) {
    console.error(`Insert failed: ${err.code}, ${err.message}`);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

#### 2.4 查询数据

import { ResultSet } from '@ohos.data.resultSet';

async function queryUsers() {
  if (!rdbStore) return [];
  const columns = ['id', 'name', 'age', 'email'];
  const predicates = new relationalStore.RdbPredicates('user');
  predicates.orderByAsc('age');  // 按年龄升序

  try {
    const resultSet: ResultSet = await rdbStore.query(predicates, columns);
    const users = [];
    while (resultSet.goToNextRow()) {
      users.push({
        id: resultSet.getLong(resultSet.getColumnIndex('id')),
        name: resultSet.getString(resultSet.getColumnIndex('name')),
        age: resultSet.getLong(resultSet.getColumnIndex('age')),
        email: resultSet.getString(resultSet.getColumnIndex('email'))
      });
    }
    resultSet.close();
    return users;
  } catch (err) {
    console.error(`Query failed: ${err.code}, ${err.message}`);
    return [];
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

### 3. 文件存储 适用于大文件(如图片、文档等)。

#### 3.1 写入文件

import { fileio } from '@ohos.fileio';
import { BusinessError } from '@ohos.base';

async function writeFile(content: string) {
  const dir = this.context.filesDir;  // 应用沙箱目录
  const path = `${dir}/user_data.txt`;
  try {
    const fd = await fileio.open(path, fileio.O_RDWR | fileio.O_CREAT);
    await fileio.write(fd, content);
    await fileio.close(fd);
    console.log('File saved');
  } catch (err) {
    console.error(`File write error: ${(err as BusinessError).code}`);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

#### 3.2 读取文件

async function readFile() {
  const path = `${this.context.filesDir}/user_data.txt`;
  try {
    const fd = await fileio.open(path, fileio.O_RDONLY);
    const stat = await fileio.stat(path);
    const buffer = new ArrayBuffer(stat.size);
    await fileio.read(fd, buffer);
    await fileio.close(fd);
    const content = String.fromCharCode.apply(null, new Uint8Array(buffer));
    return content;
  } catch (err) {
    console.error(`File read error: ${(err as BusinessError).code}`);
    return '';
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

### 4. 分布式数据管理(跨设备同步) 通过 ​​DistributedData​​ 实现多设备数据同步(需设备登录同一华为帐号)。

import { distributedData } from '@ohos.data.distributedData';

// 创建分布式数据库
const options: distributedData.KvManagerConfig = {
  bundleName: 'com.example.myapp',
  kvStoreType: distributedData.KvStoreType.SINGLE_VERSION
};

const kvManager = distributedData.createKvManager(options);

// 获取 KVStore 实例
kvManager.getKvStore('myStore')
  .then((store: distributedData.KvStore) => {
    // 写入数据
    store.put('key', 'value', (err) => {
      if (!err) console.log('Distributed data saved');
    });
  });
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

### 关键注意事项

  1. 数据安全
  • 敏感数据(如密码)使用​​@ohos.security.crypto​​ 加密。
  • 使用​​SecurityLevel.S2​​ 配置高安全级别数据库。
  1. 性能优化
  • 批量操作使用事务(RDB 的​​beginTransaction()​​)。
  • 避免主线程阻塞,使用异步 API 或 Web Worker。
  1. 存储路径
  • 应用私有目录:​​context.filesDir​​(无需权限)。
  • 公共目录:需申请​​ohos.permission.READ_USER_STORAGE​​ 等权限。
  1. 数据迁移
  • 数据库升级时,在​​onUpgrade()​​ 回调中处理表结构变更。

通过结合 Preferences(轻量)、RDB(结构化)、文件存储(大文件)和 分布式数据(跨设备),可灵活满足鸿蒙应用不同场景的本地存储需求。

分享
微博
QQ
微信
回复
6天前


相关问题
如何读取本地/预制数据库?
1935浏览 • 1回复 待解决
HarmonyOS 本地存储数据用什么?
1003浏览 • 1回复 待解决
HarmonyOS Web管理Cookie和数据存储
1469浏览 • 1回复 待解决