鸿蒙:将项目的rawfile目录下全部文件拷贝到app沙箱目录

1. 前言

  1. rawfile是鸿蒙项目中的放置资源文件夹,在该文件夹中,我们可以放图片、音乐、视频、文本等,都是可以的。
  2. 不过app访问,只能根据一个个的文件名来访问,如果想实现将整个rawfile文件夹下的文件全部拷贝到沙箱,就需要我们提前在rawfile文件夹下将全部文件打成一个压缩包。
  3. 通过zlib接口,将文件解压到沙箱目录。这便实现了拷贝流程。

2. 参考文档

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-resource-manager#closerawfiledescriptordeprecatedhttps://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-resource-manager#closerawfiledescriptordeprecated

https://developer.huawei.com/consumer/cn/doc/architecture-guides/common-v1_26-ts_93-0000002306064776https://developer.huawei.com/consumer/cn/doc/architecture-guides/common-v1_26-ts_93-0000002306064776

3. 核心思路

  1. 点击 "获取沙箱目录路径":获取并显示应用沙箱目录路径
  2. 点击 "获取缓存目录路径":获取并显示应用缓存目录路径
  3. 点击 "获取 rawfile 目录的压缩文件":从 rawfile 目录读取 "rawfile.zip" 的文件描述符
  4. 点击 "拷贝压缩文件到缓存目录":将 rawfile 中的压缩文件通过流操作复制到缓存目录
  5. 点击 "将压缩文件解压到沙箱目录":将缓存目录中的压缩文件解压到沙箱目录,并关闭文件描述符
  6. 点击 "获取沙箱目录的文件列表":读取并显示沙箱目录下的所有文件名称

4. 核心代码

复制代码
 // 拷贝压缩文件到缓存目录
  async copyCompressedFileToCacheDirectory() {
    try {
      let dest = fs.openSync(this.cacheDirectoryPath + "/rawfile.zip", fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
      let bufsize = 4096
      let buf = new ArrayBuffer(bufsize)
      let off = 0, len = 0, readedLen = 0
      /**
       * 通过buffer将rawfile文件内容copy到沙箱路径
       */
      while (len = fs.readSync(this.data!.fd, buf, { offset: this.data!.offset + off, length: bufsize })) {
        readedLen += len
        fs.writeSync(dest.fd, buf, { offset: off, length: len })
        off = off + len
        if ((this.data!.length - readedLen) < bufsize) {
          bufsize = this.data!.length - readedLen
        }
      }
      await fs.close(dest.fd)
    } catch (e) {
      console.log("拷贝失败" + e)
    }
    this.showAlertDialog("压缩文件拷贝成功")

  }

  // 将压缩文件解压到沙箱目录
  async unzipCompressedFileToSandboxDirectory() {
    // 对沙箱路径下的压缩文件进行解压
    await zlib.decompressFile(this.cacheDirectoryPath + "/rawfile.zip", this.sandboxDirectoryPath)
    await this.context.resourceManager.closeRawFd("rawfile.zip")
    console.info("解压完成")
    this.showAlertDialog("解压文件完成")
  }

5. 运行效果

6. 完整代码

Index.ets

复制代码
import { fileIo as fs } from '@kit.CoreFileKit'
import { resourceManager } from '@kit.LocalizationKit'
import { zlib } from '@kit.BasicServicesKit'

@Entry
@ComponentV2
struct Index {
  context = this.getUIContext().getHostContext()!
  @Local sandboxDirectoryPath: string = ""
  @Local cacheDirectoryPath: string = ""
  @Local data: resourceManager.RawFileDescriptor | null = null

  // 弹窗
  showAlertDialog(mes: string) {
    this.getUIContext().showAlertDialog({ message: mes })
  }

  // 获取沙箱目录路径
  getSandboxDirectoryPath() {
    this.sandboxDirectoryPath = this.context.filesDir
    this.showAlertDialog("沙箱目录路径:" + this.sandboxDirectoryPath)
  }

  // 缓存目录路径
  getCacheDirectoryPath() {
    this.cacheDirectoryPath = this.context.cacheDir
    this.showAlertDialog("缓存目录路径:" + this.cacheDirectoryPath)
  }

  // 获取rawfile目录的压缩文件
  getCompressedFileFromRawfileDirectory() {
    this.data = this.context.resourceManager.getRawFdSync("rawfile.zip")
    this.showAlertDialog("压缩文件data获取成功")
  }

  // 拷贝压缩文件到缓存目录
  async copyCompressedFileToCacheDirectory() {
    try {
      let dest = fs.openSync(this.cacheDirectoryPath + "/rawfile.zip", fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
      let bufsize = 4096
      let buf = new ArrayBuffer(bufsize)
      let off = 0, len = 0, readedLen = 0
      /**
       * 通过buffer将rawfile文件内容copy到沙箱路径
       */
      while (len = fs.readSync(this.data!.fd, buf, { offset: this.data!.offset + off, length: bufsize })) {
        readedLen += len
        fs.writeSync(dest.fd, buf, { offset: off, length: len })
        off = off + len
        if ((this.data!.length - readedLen) < bufsize) {
          bufsize = this.data!.length - readedLen
        }
      }
      await fs.close(dest.fd)
    } catch (e) {
      console.log("拷贝失败" + e)
    }
    this.showAlertDialog("压缩文件拷贝成功")

  }

  // 将压缩文件解压到沙箱目录
  async unzipCompressedFileToSandboxDirectory() {
    // 对沙箱路径下的压缩文件进行解压
    await zlib.decompressFile(this.cacheDirectoryPath + "/rawfile.zip", this.sandboxDirectoryPath)
    await this.context.resourceManager.closeRawFd("rawfile.zip")
    console.info("解压完成")
    this.showAlertDialog("解压文件完成")
  }

  // 获取沙箱目录的文件列表
  getFileListInSandboxDirectory() {
    let files = fs.listFileSync(this.sandboxDirectoryPath,);
    this.showAlertDialog(files.join("\n"))
  }

  build() {
    Column({ space: 100 }) {
      Text("请依次点击下方按钮")
        .fontSize(28)
        .fontWeight(FontWeight.Bold)
      Column({ space: 20 }) {
        Text("沙箱目录路径:" + this.sandboxDirectoryPath)
        Button("1、获取沙箱目录路径")
          .onClick(() => {
            this.getSandboxDirectoryPath()
          })
        Text("缓存目录路径:" + this.cacheDirectoryPath)
        Button("2、获取缓存目录路径")
          .onClick(() => {
            this.getCacheDirectoryPath()
          })
        Text("压缩文件data长度:" + this.data?.length)
        Button("3、获取rawfile目录的压缩文件")
          .onClick(() => {
            this.getCompressedFileFromRawfileDirectory()
          })

        Button("4、拷贝压缩文件到缓存目录")
          .onClick(() => {
            this.copyCompressedFileToCacheDirectory()
          })
        Button("5、将压缩文件解压到沙箱目录")
          .onClick(() => {
            this.unzipCompressedFileToSandboxDirectory()
          })
        Button("6、获取沙箱目录的文件列表")
          .onClick(() => {
            this.getFileListInSandboxDirectory()
          })
      }

    }
    .width("100%")
    .height("100%")
    .justifyContent(FlexAlign.Center)

  }
}

觉得有帮助可以点赞或收藏

相关推荐
AI备忘录1 天前
(十九)华为华三锐捷迈普思科 交换机链路聚合配置命令(LACP/静态聚合五厂商对照)
运维·服务器·网络·网络协议·tcp/ip·华为
贾伟康1 天前
【时光清单|19】HarmonyOS ArkTS 回归测试实战:覆盖启动、空数据、异常输入和重复点击
软件测试·harmonyos·arkts·回归测试·hypium
坚果的博客1 天前
Flutter OHOS 环境搭建实战:oh-3.44.9-dev 从 0 到 1 完整记录
flutter·华为·harmonyos
坚果的博客1 天前
认识 CPF-RN:React Native 鸿蒙官方社区与四大核心仓库
react native·react.js·harmonyos
大雷神1 天前
HarmonyOS ArkGraphics 2D可变帧率实操——同屏对比30、60和90 FPS动画
华为·harmonyos
OH_TPC1 天前
【鸿蒙优选三方库】@react-native-ohos/react-native-fast-image:高性能图片加载与缓存组件
缓存·华为·harmonyos·鸿蒙
贾伟康1 天前
【句匠|03】HarmonyOS ArkTS 每日打卡实战:实现连续天数、补签边界和本地日期判断
harmonyos·arkts·本地存储·每日打卡·学习应用
小雨青年1 天前
【HarmonyOS 7 平行视界深度实战】02 从普通页面到第一个平行视界 Demo
华为·harmonyos
~远在太平洋~1 天前
06-鸿蒙系统 uitest UI 自动化指南
ui·自动化·harmonyos
OH_TPC1 天前
OpenHarmony平台RN三方库适配情况
华为·harmonyos·鸿蒙