鸿蒙java的app开发项目,有两种图片存放路径一种是resouece/base/media, 一种是resource/base/rawfile。 第一种media下的图片资源会编译进hap包种,而且建立资源引用号,可以通过resourceTable.resId引用。 第二种rawfile就不能通过resourceTable引用,只能通过读文件方式读取。
方式一
通过绝对路径,也就是hap包安装后的相对路径读取,rawfile安装路径格式是:
assets/entry/resources/rawfile/image/raw文件名称
这样可以通过classloader方式读取文件。如:
//组装文件路径
String filePath = String.format("assets/entry/resources/rawfile/image/%s", fileName);
//通过classloader读取文件,返回一个流对象
InputStream snputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
if(snputStream == null) {
return null;
}
方式二
鸿蒙提供了一个ResourceManager资源管理器,通过该资源管理器可以读取到该hap包下的所有resouece目录下的资源文件。 api路径:
ohos.global.resource.ResourceManager
使用方式如下:
//通过context获取一个resourceManager对象
ResourceManager resourceManager = this.getApplicationContext().getResourceManager();
//通过resourceManager对象获取rawfile文件对象
RawFileEntry rawFileEntry = resourceManager.getRawFileEntry(String.format("resources/rawfile/image/%s", fileName));
try {
//返回文件对应的resouce描述对象
Resource resource = rawFileEntry.openRawFile();
//文件内容长度
int length = resource.available();
byte [] buffer = new byte[length];
//读取文件内容到一个byte缓冲
resource.read(buffer, 0, length);
} catch (IOException e) {
log.err("读取图片资源失败," + e);
}