HarmonyOS如何进行数据文件存储

有一份json文件需要预先放置在应用中,在使用的时候再读取这份文件数据。目前不清楚这份json文件应该放置在应用中哪个目录下合适 rawfile可以?如何读取?

HarmonyOS
2024-08-09 16:27:16
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

json文件可以放在rawfile目录下,同步和异步获取json文件内容的样例代码如下:点击get按钮可以获取json文件内容,控制台打印。

import { Context } from '@ohos.abilityAccessCtrl'; 
import buffer from '@ohos.buffer'; 
@Entry 
@Component 
struct Index { 
  private context:Context = getContext(this) ; 
  private str:string = '' 
  getRawFile(): ESObject{ 
    //调用getRawFileContent接口获取json文件内容,并读为string 
    getContext(this).resourceManager.getRawFileContent("data.json",(err,data)=>{ 
      try { 
        this.str = buffer.from(data.buffer).toString(); 
        console.info(JSON.stringify(this.str)) 
      }catch (e){ 
        console.info(JSON.stringify(e)) 
      } 
    }) 
    //也可以调用getRawFileContentSync接口获取json文件内容,并读为string 
    try { 
      let data: Uint8Array= this.context.resourceManager.getRawFileContentSync("data.json"); 
      this.str = buffer.from(data.buffer).toString(); 
    } catch (e) { 
      console.info(JSON.stringify(e)) 
    } 
    // string转为ESObject 
    let obj:ESObject = JSON.parse(this.str) 
    return obj 
  } 
  build() { 
    Column() { 
      Button("get") 
        .onClick(() => { 
          this.getRawFile() 
        }) 
    }.width('100%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
分享
微博
QQ
微信
回复
2024-08-09 18:08:34
相关问题
HarmonyOS 如何进行数据持久化
951浏览 • 1回复 待解决
FA卡片如何进行数据交互
2639浏览 • 1回复 待解决
PolarDB 如何进行数据通信?
3498浏览 • 1回复 待解决
TaskPool线程中如何进行数据库操作?
950浏览 • 1回复 待解决
鸿蒙Js如何进行信息存储
4020浏览 • 1回复 待解决
数据文件中写入数据的方法
896浏览 • 1回复 待解决
创建数据文件的方法有哪些?
1186浏览 • 1回复 待解决
读取数据文件的方法有哪些
993浏览 • 1回复 待解决
求告知删除数据文件的方法
941浏览 • 1回复 待解决
App Sqlite 数据库初使化数据文件
944浏览 • 1回复 待解决
HarmonyOS 看不到手机内部的数据文件
658浏览 • 1回复 待解决
HarmonyOS 如何进行文本文件读取?
899浏览 • 1回复 待解决
HarmonyOS 如何进行深层次数据更新
963浏览 • 1回复 待解决