关于使用getRawFileContentSync提示Rawfile path is invalid的问题,从官方文档中无法定位出是路径给错了还是使用的方式不对。
错误日志:
07-19 11:37:22.088 13435-13435 C01e00/ResourceManagerJs E Failed to get rawfile by city_code.json
07-19 11:37:22.088 13435-13435 A0ff00/[QZD] E CityCodeHelper, getRawFileContentSync failed, error code: 9001005, message: Rawfile path is invalid.
具体代码如下:
import { JSON, util } from '@kit.ArkTS'
import { CityCodeBean } from '../bean/CityCodeBean';
import { CityCodeFileDataSource } from '../datasource/CityCodeFileDataSource';
import { common } from '@kit.AbilityKit'
import { BusinessError } from '@ohos.base';
import { log } from 'lib_common/src/main/ets/utils/Logger';
const TAG = 'CityCodeHelper'
class CityCodeHelper {
constructor() {
CityCodeFileDataSource.init(getContext(this) as common.ApplicationContext)
}
/*
* 此方法提供的CityCodeBean 类型绝对安全,无需再次转换
* */
getCityCodes():Array<CityCodeBean> {
const cityCodes = CityCodeFileDataSource.getCityCodes()
if (cityCodes == null) {
return this.getLocalCityCodeTransformer()
}else {
let safeCityCodes:Array<CityCodeBean> = []
cityCodes.forEach((item)=>{
safeCityCodes.push(this.transform(item))
})
return safeCityCodes
}
}
/*
* 保存网络上同步得到的城市码表数据
* @param cityCodes: 原始数据表弱类型对象,但是必须符合`CityCodeBean`的数据结构
* @param version:获取到的版本号
* */
saveCityCodes(cityCodes:Array<CityCodeBean>, version:number) {
CityCodeFileDataSource.saveCityCodes(cityCodes, version)
}
private getLocalCityCodeTransformer():Array<CityCodeBean> {
try {
let rawFile: Uint8Array = getContext(this).resourceManager.getRawFileContentSync('city_code.json');
let localCityCodeStr: string = util.TextDecoder.create("utf-8", { ignoreBOM: true }).decodeWithStream(rawFile);
let localCityCodes:Array<CityCodeBean> = []
const _cityCodes:Array<CityCodeBean> = JSON.parse(localCityCodeStr) as Array<CityCodeBean>
_cityCodes.forEach((item)=>{
localCityCodes.push(this.transform(item))
})
return localCityCodes
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
log.error(TAG, `getRawFileContentSync failed, error code: ${code}, message: ${message}.`)
return []
}
}
private transform(data:Object):CityCodeBean {
let original:CityCodeBean = data as CityCodeBean
let subs:Array<CityCodeBean> | null = []
if (Array.isArray(original.sub)) {
original.sub?.forEach((item)=>{
subs?.push(this.transform(item))
})
}else {
subs = null
}
return new CityCodeBean(
original.id,
original.name,
original.shortName,
original.type,
original.parentId,
original.levelType,
original.pinyin,
original.shortPinyin,
subs
)
}
}
export const cityCodeInstance = new CityCodeHelper()
尝试下如下办法:getContext(this)整个context默认为entry的context,需要指定hsp的context,示例如下:
在context后加上createModuleContext(‘library’) ,library为module.json5中的name修改后:
参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/application-dev-guide-V5?catalogVersion=V5