HarmonyOS鸿蒙Next中麻烦问下我想获取 rawfile 文件夹我已有的 db 数据库用什么办法解决

HarmonyOS鸿蒙Next中麻烦问下我想获取 rawfile 文件夹我已有的 db 数据库用什么办法解决 麻烦问下我想获取 rawfile 文件夹我已有的 db 数据库用什么办法解决

4 回复

资源管理模块resourceManager,根据当前的Configuration配置,获取应用资源信息读取接口

可以参考一下https://developer.huawei.com/consumer/cn/doc/architecture-guides/tools-v1_2-ts_43-0000002346637729#section6522121212564

更多关于HarmonyOS鸿蒙Next中麻烦问下我想获取 rawfile 文件夹我已有的 db 数据库用什么办法解决的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


【背景知识】

[@ohos.resourceManager](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-resource-manager):本模块提供资源获取能力。根据当前的Configuration配置,获取最匹配的应用资源或系统资源。具体匹配规则参考资源匹配

【参考方案】

可参考加载预置数据库刷新文章列表示例,通过[@ohos.resourceManager](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-resource-manager)加载本地预置数据库(或从网络下载的数据库),实现文章列表刷新的功能。

  1. 在EntryAbility组件初始化OnCreate时,使用getRawFdfs.write实现copyDBToSandbox方法将rawfile目录下的db文件拷贝至应用沙箱。
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  AppStorage.setOrCreate<Context>('context', this.context);
  getDBOperatorManager().copyDBToSandbox(this.context, 'book.db');
}
  1. 在页面加载aboutToAppear时,使用relationalStore.getRdbStore实现readBookList接口通过RdbStore读取沙箱下db数据库文件,实例化Book对象,创建BookArray,存入读取到的数据。
aboutToAppear(): void {
  getDBOperatorManager()
    .readBookList(this.context, 3)
    .then(bookArray => {
      this.data.reloadData(bookArray);
      this.filterVipData(bookArray);
    });
}

在HarmonyOS Next中,可通过ResourceManager访问rawfile目录下的数据库文件。使用getRawFileContent方法获取文件描述符后,利用ArkTS的数据库API打开。示例代码:

import database from '@ohos.data.database';

let context = getContext(this) as common.UIAbilityContext;
let resourceManager = context.resourceManager;

resourceManager.getRawFileContent('your_db.db').then(fd => {
  let db = database.openDatabase({ name: 'your_db.db', fd: fd });
  // 数据库操作
});

需在module.json5中声明数据库权限。

在HarmonyOS Next中,可以通过ResourceManager访问rawfile目录下的数据库文件。具体步骤:

  1. 使用getRawFileContent()方法读取数据库文件为ArrayBuffer
let resourceManager = getContext().resourceManager;
let dbBuffer = await resourceManager.getRawFileContent('your_database.db');
  1. 将ArrayBuffer转换为Uint8Array:
let dbData = new Uint8Array(dbBuffer);
  1. 通过文件管理接口将数据写入应用沙箱路径:
import fs from '@ohos.file.fs';
let cacheDir = getContext().cacheDir;
let dbPath = cacheDir + '/your_database.db';
let file = fs.openSync(dbPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
fs.writeSync(file.fd, dbData);
fs.closeSync(file);
  1. 使用关系型数据库API打开数据库:
import relationalStore from '@ohos.data.relationalStore';
let rdbStore = await relationalStore.getRdbStore(getContext(), {
  name: 'your_database.db',
  path: dbPath
});

注意:rawfile中的数据库文件是只读的,需要复制到应用可读写目录后才能进行数据库操作。

回到顶部