[Harmony]大文件持久化

1.添加权限

在module.json5文件中添加权限

javascript 复制代码
"requestPermissions": [
  {
    "name": "ohos.permission.READ_WRITE_USER_FILE", // 读写用户数据
    "reason": "$string:read_write_user_file_reason",
    "usedScene": {
      "abilities": ["MFLargeDataStorage"],
      "when": "always"
    }
  }
]

string.json

javascript 复制代码
{
  "string": [
    {
      "name": "read_write_user_file_reason",
      "value": "读写用户文件"
    }
  ]
}

2.封装大文件数据持久工具

TypeScript 复制代码
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
import ConsoleLog from '../extension/ConsoleLog';
import { buffer } from '@kit.ArkTS';

class MFLargeDataStorage {
  private static readonly FILE_NAME = 'user_data.json';
  private static _context: common.UIAbilityContext;

  static setContext(abilityContext: common.UIAbilityContext): void {
    MFLargeDataStorage._context = abilityContext;
  }

  private static getFilePath(): string {
    if (!MFLargeDataStorage._context) {
      throw new Error('Context not initialized');
    }
    return `${MFLargeDataStorage._context.filesDir}/${MFLargeDataStorage.FILE_NAME}`;
  }

  static async saveUserJson(data: object): Promise<void> {
    const filePath = MFLargeDataStorage.getFilePath();
    const jsonStr = JSON.stringify(data);
    try {
      const file = await fs.open(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
      await fs.write(file.fd, jsonStr);
      await fs.close(file.fd);
    } catch (err) {
      ConsoleLog.error(`[MFLargeDataStorage] save error: ${(err as BusinessError).message}`);
    }
  }

  static async saveUserJsonString(jsonStr: string): Promise<void> {
    const filePath = MFLargeDataStorage.getFilePath();
    try {
      const file = await fs.open(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
      await fs.write(file.fd, jsonStr);
      await fs.close(file.fd);
    } catch (err) {
      ConsoleLog.error(`[MFLargeDataStorage] save error: ${(err as BusinessError).message}`);
    }
  }

  static async loadUserJson(): Promise<string> {
    const filePath = MFLargeDataStorage.getFilePath();
    try {
      if (!await fs.access(filePath)) {
        return "";
      }
      const file = await fs.open(filePath, fs.OpenMode.READ_ONLY);
      const stat = await fs.stat(filePath);
      const buf = new ArrayBuffer(stat.size);
      await fs.read(file.fd, buf);
      await fs.close(file.fd);
      // 使用buffer模块的from和toString方法
      const str = buffer.from(buf).toString('utf-8');
      return str;
    } catch (err) {
      ConsoleLog.error(`[MFLargeDataStorage] load error: ${(err as BusinessError).message}`);
      return "";
    }
  }
}

export default MFLargeDataStorage;

3.使用示例

TypeScript 复制代码
import common from '@ohos.app.ability.common';
import ConsoleLog from '../support/extension/ConsoleLog';
import MFLargeDataStorage from '../support/data/MFLargeDataStorage';

interface UserItem {
  name: string;
  age: number;
}

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;

  aboutToAppear() {
    if (!this.context) {
      ConsoleLog.error('无效的上下文对象');
      return;
    }
    MFLargeDataStorage.setContext(this.context);
  }

  build() {
    RelativeContainer() {
      Column() {
        Button('保存大文件')
          .onClick(async () => {
            const userData: UserItem = { name: "张三", age: 25 };
            try {
              await MFLargeDataStorage.saveUserJson(userData);
            } catch (err) {
              ConsoleLog.error('保存失败:', err);
            }
          })

        Button('获取大文件')
          .onClick(async () => {
            const loadedData = await MFLargeDataStorage.loadUserJson();
            ConsoleLog.log(loadedData); // 输出: {name: "张三", age: 25}
          })
      }
    }
    .height('100%')
    .width('100%')
  }
}
相关推荐
威哥爱编程7 小时前
【鸿蒙开发实战篇】如何基于一多能力实现响应式布局
harmonyos·arkts·arkui
威哥爱编程8 小时前
【鸿蒙开发实战篇】如何实现高级图片滤镜
harmonyos·arkts·arkui
威哥爱编程8 小时前
【鸿蒙开发实战篇】强大的跨应用数据分享与应用内文件共享
harmonyos·arkts·arkui
威哥爱编程8 小时前
【鸿蒙开发实战篇】如何利用 3D渲染引擎实现高性能动态滤镜特效
harmonyos·arkts·arkui
威哥爱编程8 小时前
【鸿蒙开发实战篇】滤镜效果图高效分享
harmonyos·arkts·arkui
威哥爱编程8 小时前
【鸿蒙开发实战篇】鸿蒙跨设备的碰一碰文件分享
harmonyos·arkts·arkui
威哥爱编程8 小时前
【鸿蒙开发实战篇】实现锁屏沉浸实况窗案例
harmonyos·arkts·arkui
威哥爱编程8 小时前
【鸿蒙开发实战篇】基于AVPlayer播放网络视频案例
harmonyos·arkts·arkui
威哥爱编程8 小时前
【鸿蒙开发实战篇】实现剪切板复制粘贴的功能
harmonyos·arkts·arkui
威哥爱编程9 小时前
【鸿蒙开发实战篇】鸿蒙6 AI智能体集成实战
harmonyos·arkts·arkui