HarmonyOS 读取.properties文件的api?

有读取.properties文件的api吗?类似java的Properties类。

阅读 438
1 个回答

不属于应用的配置文件是没办法通过API进行读取的。为了便于管理,自定义的配置文件(如config.json)建议统一放到resources资源目录下,通过在aboutToAppear方法中编写,可在build加载前,把config配置文件内容加载出来并用fs,buffer流进行读取,转化为自定义的一个ConfigFile实体类,再通过实体类获取里面的内容,参考下面代码:

async aboutToAppear() {
  let json = await readWriteFileWithStream()
  let list = JSON.parse(JSON.stringify(json)) as ConfigFile
}

async function readWriteFileWithStream(): Promise<ConfigFile> {
  return new Promise((resolve: Function, reject: Function) => {
    let file = fs.openSync('文件路径', fs.OpenMode.READ_WRITE);
    let arrayBuffer = new ArrayBuffer(4096);
    fs.read(file.fd, arrayBuffer).then((readLen: number) => {
      console.info("read file data succeed");
      let buf = buffer.from(arrayBuffer, 0, readLen);
      let json: ConfigFile = JSON.parse(buf.toString())
      resolve(json)
    }).catch((err: BusinessError) => {
      console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
    }).finally(() => {
      fs.closeSync(file);
    });
  })
}
logo
HarmonyOS
子站问答
访问
宣传栏