HarmonyOS 如何把rawfile目录下面的文件夹拷贝到沙盒目录

如何把rawfile目录下面的文件夹拷贝到沙盒目录,rawfile有个文件夹如何把rawfile目录下面的文件夹拷贝到沙盒目录。

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

参考示例:

import fs from '@ohos.file.fs';
import { Context } from '@ohos.abilityAccessCtrl';
import zlib from '@ohos.zlib';

@Entry
@Component
struct Index {
  @State context: Context = getContext(this);

  build() {
    Row() {
      Column() {

        Button('复制图片到沙箱')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            getContext(this).resourceManager.getRawFileContent('666.png', (_err, value) => {
              let myBuffer: ArrayBufferLike = value.buffer
              //沙箱路径
              let filePath = this.context.filesDir + "/66.png";
              console.log("testTag-filePath:" + filePath);
              let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
              let writeLen = fs.writeSync(file.fd, myBuffer);
              console.info("testTag-write data to file succeed and size is:" + writeLen);
              fs.closeSync(file);
            });
          })

        Button('复制zip到沙箱,并解压zip', { type: ButtonType.Normal, stateEffect: true })
          .borderRadius(8)
          .backgroundColor(0x317aff)
          .width(90)
          .height(40)
          .onClick(() => {
            /**
             * 通过fd来进行拷贝,避免文件过大的内存占用问题
             * data.fd是hap包的fd,data.offset表示目标文件在hap包中的偏移,data.length表示目标文件的长度
             */
            this.context.resourceManager.getRawFd("picture.zip", (err, data) => {
              let sandboxPath = this.context.filesDir
              console.log("沙箱路径:" + sandboxPath)
              fs.mkdtempSync(sandboxPath + "/XXXXXX")
              let filePath = this.context.tempDir + "/bfpicture.zip"
              console.log("压缩文件路径:" + filePath)
              let dest = fs.openSync(filePath, 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(data.fd, buf, { offset: data.offset + off, length: bufsize })) {
                readedLen += len
                fs.writeSync(dest.fd, buf, { offset: off, length: len })
                off = off + len
                if ((data.length - readedLen) < bufsize) {
                  bufsize = data.length - readedLen
                }
              }
              fs.close(dest.fd)
              // 对沙箱路径下的压缩文件进行解压
              zlib.decompressFile(filePath, sandboxPath)
              this.context.resourceManager.closeRawFd("bfpicture.zip")
            })
          })
          .width('100%')
      }
      .height('100%')
    }
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS rawfile文件拷贝到沙箱
219浏览 • 1回复 待解决
HarmonyOS 拷贝文件
169浏览 • 1回复 待解决
HarmonyOS 如何文件存储公共目录
176浏览 • 1回复 待解决
怎样在根目录中创建文件夹
4375浏览 • 1回复 待解决