在鸿蒙系统中,rawfile资源目录文件无法直接获取路径,如需要对该资源进行文件级的操作(如系统分享api,参数是fileuri),则需先通过resourceManager.getRawFileContent 读取内容后写入沙箱,之后对沙盒文件进行相关的操作。
下面的代码实现将rawfile资源目录中的文件拷贝至沙盒目录
import { resourceManager } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit';
copyRawFileToSandBox() {
let context = getContext(this) as common.UIAbilityContext;
// 读取 rawfile 文件内容
const rawFileContent = context.resourceManager.getRawFileContentSync('example.jpg');
// 写入沙箱后获取路径
const targetPath = `${context.filesDir}/example.jpg`;
// const fileStream = fileIo.createStreamSync(targetPath, 'w+');
let file = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
let writeLen = fileIo.writeSync(file.fd, (rawFileContent as Uint8Array).buffer);
console.info("write data to file succeed and size is:" + writeLen);
fileIo.closeSync(file);
}