const context = getContext(this);
try {
// 获取资源ID
const resourceId = $r('app.media.icon').id;
// 读取资源内容
const mediaData = await context.resourceManager.getMediaContent(resourceId);
} catch (err) {
console.error(`资源读取失败: ${err.code}, ${err.message}`);
}
import fs from '@ohos.file.fs';
// 目标沙盒路径
const targetPath = context.filesDir + '/icon.png';
// 创建并写入文件
let file = await fs.open(targetPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
await fs.write(file.fd, mediaData);
fs.close(file.fd);
console.log(`可用路径: ${targetPath}`);
// 示例输出: /data/storage/.../files/icon.png
// 预定义资源映射表
const resMap = {
icon1: $r('app.media.icon1'),
icon2: $r('app.media.icon2')
};
// 动态获取ID
function getResId(name: keyof typeof resMap) {
return resMap[name].id;
}
// 使用示例
console.log(getResId('icon1')); // 输出静态资源ID