【HarmonyOS】鸿蒙将资源文件夹Resource-RawFile下的文件存放到沙箱目录下

【HarmonyOS】鸿蒙将资源文件夹Resource-RawFile下的文件存放到沙箱目录下

一、问题背景

应用开发中,我们经常会遇到一些文件原先是放在资源文件夹 rawfile下,但是逻辑处理时,需要转移到本地沙箱才能操作。这种情况下,就需要将将资源文件夹Resource-RawFile下的文件存放到沙箱目录下。

二、鸿蒙资源文件和沙箱的概念

在鸿蒙中,应用仅能保存文件到"应用文件目录"下,根据目录的使用规范和注意事项来选择将数据保存到不同的子目录中。

这样的设定与安卓和苹果目前一致。应用沙箱的概念,可以保证数据访问的安全性。

在鸿蒙系统中,文件存储分为不同的域,如应用内部存储(应用私有目录)和外部存储(公共目录等)。应用内部存储是应用私有的,其他应用通常无法访问。外部存储可以在用户授权的情况下被多个应用访问。

注意:

不要使用绝对路径拼接系统文件路径,否则可能导致后续应用版本因应用文件路径变化导致不兼容问题。应该是用context去动态获取。

而rawfile是一种资源文件类型,通常在应用开发过程中作为原始文件被打包进应用的资源目录。它在 APK(安卓应用安装包)或者鸿蒙应用安装包(HAP)中是只读的。

三、解决方案思路

1.首先我们需要通过getRawFileContentSync读取rawfile下目标文件的内容val

dart 复制代码
      let val: Uint8Array = context.resourceManager.getRawFileContentSync("test.zip");

2.之后创建本地沙箱的文件对象fileTarget

dart 复制代码
  let pathDir: string = context.filesDir; // /data/storage/el2/base/haps/entry/files
      console.info(this.TAG, "pathDir: " + pathDir);
      // 待拷贝文件沙箱路径
      let filePath: string = pathDir + '/test.zip';
      console.info(this.TAG, "filePath: " + filePath);
      // 若文件不存在,则创建文件。
      let fileTarget = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);

3.将val目标文件内容写入文件对象即可

dart 复制代码
      let writeLen = fs.writeSync(fileTarget.fd, val.buffer as ArrayBuffer);

最后记得关闭fs

dart 复制代码
 fs.closeSync(fileTarget);

完整源码

dart 复制代码
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo as fs } from '@kit.CoreFileKit';

@Entry
@Component
struct SandboxPage {
  private TAG: string = "SandboxPage";

  onCopyRawFileToLocal = ()=>{
    let context = getContext(this) as common.UIAbilityContext; // 获取设备A的UIAbilityContext信息
    try {
      let val: Uint8Array = context.resourceManager.getRawFileContentSync("test.zip");
      console.info(this.TAG, "getRawFileContentSync done");
      let pathDir: string = context.filesDir; // /data/storage/el2/base/haps/entry/files
      console.info(this.TAG, "pathDir: " + pathDir);
      // 待拷贝文件沙箱路径
      let filePath: string = pathDir + '/test.zip';
      console.info(this.TAG, "filePath: " + filePath);
      // 若文件不存在,则创建文件。
      let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      console.info(this.TAG, "file done");
      let writeLen = fs.writeSync(file.fd, val.buffer as ArrayBuffer);
      console.info(this.TAG, "write data to file succeed and size is:" + writeLen);
      fs.closeSync(file);
    } catch (error) {
      let code = (error as BusinessError).code;
      let message = (error as BusinessError).message;
      console.error(this.TAG,`getRawFileContentSync failed, error code: ${code}, message: ${message}.`);
    }

  }

  build() {
    RelativeContainer() {
      Text("点击拷贝zip到本地沙箱下")
        .id('SandboxPageHelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(this.onCopyRawFileToLocal)
    }
    .height('100%')
    .width('100%')
  }
}

验证zip拷贝成功:
1. IDE右下角找到 Device File Browser

2.根据你的app包名,找到zip的位置

相关推荐
亚历克斯神3 小时前
Flutter for OpenHarmony: Flutter 三方库 mutex 为鸿蒙异步任务提供可靠的临界资源互斥锁(并发安全基石)
android·数据库·安全·flutter·华为·harmonyos
钛态3 小时前
Flutter 三方库 smartstruct 鸿蒙化字段映射适配指南:介入静态预编译引擎扫除视图及数据模型双向强转类型错乱隐患,筑稳如磐石的企业级模型治理防线-适配鸿蒙 HarmonyOS ohos
flutter·华为·harmonyos
键盘鼓手苏苏3 小时前
Flutter 组件 csv2json 适配鸿蒙 HarmonyOS 实战:高性能异构数据转换,构建 CSV 流式解析与全栈式数据映射架构
flutter·harmonyos·鸿蒙·openharmony
雷帝木木3 小时前
Flutter 三方库 hrk_logging 的鸿蒙化适配指南 - 实现标准化分层日志记录、支持多目的地输出与日志分级过滤
flutter·harmonyos·鸿蒙·openharmony·hrk_logging
左手厨刀右手茼蒿3 小时前
Flutter 三方库 dio_compatibility_layer 的鸿蒙化适配指南 - 实现 Dio 跨主版本的平滑迁移、支持遗留拦截器兼容与网络请求架构稳定升级
flutter·harmonyos·鸿蒙·openharmony·dio_compatibility_layer
雷帝木木3 小时前
Flutter 三方库 hashids2 基于鸿蒙安全内核的深度隐匿映射适配:数字指纹泄露防御层、生成短小精悍唯一不可逆加盐哈希,护航全链路请求 URL 隐私-适配鸿蒙 HarmonyOS ohos
安全·flutter·harmonyos
HwJack205 小时前
HarmonyOS响应式布局与窗口监听:让界面像呼吸般灵动的艺术
ubuntu·华为·harmonyos
王码码20356 小时前
Flutter 组件 inappwebview_cookie_manager 适配 鸿蒙Harmony 实战 - 驾驭核心大 Web 容器缓存隧道、构建金融级政企应用绝对防串号跨域大隔离基座
flutter·harmonyos·鸿蒙·openharmony·inappwebview_cookie_manager
左手厨刀右手茼蒿6 小时前
Flutter 组件 ews 的适配 鸿蒙Harmony 实战 - 驾驭企业级 Exchange Web Services 协议、实现鸿蒙端政企办公同步与高安通讯隔离方案
flutter·harmonyos·鸿蒙·openharmony
键盘鼓手苏苏6 小时前
Flutter 组件 spry 适配鸿蒙 HarmonyOS 实战:轻量化 Web 框架,构建高性能端侧微服务与 Middleware 治理架构
flutter·harmonyos·鸿蒙·openharmony