【Harmony OS】【ARK UI】輕量級數據存儲

 1、輕量級數據存儲概述

1.1 輕量級數據存儲適用於對Key-Value結構的數據進行存取和持久化操作。應用獲取某個輕量級存儲對象後,該存儲對象中的數據將會被緩存在內存中,以便應用獲得更快的數據存取速度。應用也可以將緩存的數據再次寫回文本文件中進行持久化存儲,由於文件讀寫將產生不可避免的系統資源開銷,建議應用減少對持久化文件的讀寫頻率。
參考網址:
https://developer.harmonyos.com/cn/docs/documentation/doc-guides/database-preference-overview-0000000000030086

 

2、使用場景

2.1 輕量級數據存儲功能通常用於保存應用的一些常用配置信息,並不適合需要存儲大量數據和頻繁改變數據的場景。應用的數據保存在文件中,這些文件可以持久化地存儲在設備上。需要注意的是,應用訪問的實例包含文件所有數據,這些數據會一直加載在設備的內存中,直到應用主動從內存中將其移除前,應用可以通過Preferences的API進行數據操作。
輕量級存儲爲應用提供key-value鍵值型的文件數據處理能力,支持應用對數據進行輕量級存儲及查詢。數據存儲形式爲鍵值對,鍵的類型爲字符串型,值的存儲數據類型包括數字型、字符型、布爾型。

 

3、代碼實現

import dataStorage from '@ohos.data.storage'
import ability_featureAbility from '@ohos.ability.featureAbility'

@Entry
@Component
struct MyStorage {
  @State path: string= "";

  public PushData() {
    var that = this;
    var context = ability_featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
        that.path = data;
        let storage = dataStorage.getStorageSync(that.path + '/mystore')
        storage.putSync('startup', 'auto')
        storage.flushSync()
        console.log("flushSync成功")
      }).catch((error) => {
      console.log('Failed to obtain the file directory. Cause: ' + error.message);
    })

  }

  public ReadData() {
    let storage = dataStorage.getStorageSync(this.path + '/mystore')
    let promise = storage.get('startup', 'default')
    promise.then((value) => {
      console.log("值爲 " + value)
    }).catch((err) => {
      console.log("Get the value of startup failed with err: " + err)
    })

  }

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Text('存儲數據')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .onClick(this.PushData.bind(this))
      Text('讀取數據')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .onClick(this.ReadData.bind(this))
    }
    .width('100%')
    .height('100%')
  }
}

 

4.運行效果

cke_4995.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章