開源 Arkts 鴻蒙應用 開發(六)數據持久--文件和首選項存儲

?文章的目的為了記錄使用Arkts?進行Harmony?app?開發學習的經歷。本職為嵌入式軟件開發,公司安排開發app,臨時學習,完成app的開發。開發流程和要點有些記憶模糊,趕緊記錄,防止忘記。

?相關鏈接:

開源 Arkts 鴻蒙應用 開發(一)工程文件分析-CSDN博客

開源 Arkts 鴻蒙應用 開發(二)封裝庫.har制作和應用-CSDN博客

開源 Arkts 鴻蒙應用 開發(三)Arkts的介紹-CSDN博客

開源 Arkts 鴻蒙應用 開發(四)布局和常用控件-CSDN博客

開源 Arkts 鴻蒙應用 開發(五)控件組成和復雜控件-CSDN博客

?推薦鏈接:

開源 java android app 開發(一)開發環境的搭建-CSDN博客

開源 java android app 開發(二)工程文件結構-CSDN博客

開源 java android app 開發(三)GUI界面布局和常用組件-CSDN博客

開源 java android app 開發(四)GUI界面重要組件-CSDN博客

開源 java android app 開發(五)文件和數據庫存儲-CSDN博客

開源 java android app 開發(六)多媒體使用-CSDN博客

開源 java android app 開發(七)通訊之Tcp和Http-CSDN博客

開源 java android app 開發(八)通訊之Mqtt和Ble-CSDN博客

開源 java android app 開發(九)后臺之線程和服務-CSDN博客

開源 java android app 開發(十)廣播機制-CSDN博客

開源 java android app 開發(十一)調試、發布-CSDN博客

開源 java android app 開發(十二)封庫.aar-CSDN博客

推薦鏈接:

開源C# .net mvc 開發(一)WEB搭建_c#部署web程序-CSDN博客

開源 C# .net mvc 開發(二)網站快速搭建_c#網站開發-CSDN博客

開源 C# .net mvc 開發(三)WEB內外網訪問(VS發布、IIS配置網站、花生殼外網穿刺訪問)_c# mvc 域名下不可訪問內網,內網下可以訪問域名-CSDN博客

開源 C# .net mvc 開發(四)工程結構、頁面提交以及顯示_c#工程結構-CSDN博客

開源 C# .net mvc 開發(五)常用代碼快速開發_c# mvc開發-CSDN博客

本章節內容如下:

1.? 文件存儲

2.? 首選項存儲

一、文件讀寫,實現了按鍵將對話框數據對寫入文件,按鍵讀取文件數據到對話框。寫入后,關閉app,重新打開后再讀出,驗證文件存取成功。

1.1? 寫入文件和讀出文件代碼

writeToFile() {try {let file = fs.openSync(this.filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);fs.writeSync(file.fd, this.inputText);fs.closeSync(file.fd);this.outputText = '內容已成功寫入文件';console.log('寫入文件成功');} catch (error) {console.error(`寫入文件失敗: ${error.message}`);this.outputText = '寫入文件失敗';}}readFromFile() {try {if (!fs.accessSync(this.filePath)) {this.outputText = '文件不存在';return;}let file = fs.openSync(this.filePath, fs.OpenMode.READ_ONLY);let stat = fs.statSync(this.filePath);let arrayBuffer = new ArrayBuffer(stat.size);fs.readSync(file.fd, arrayBuffer);fs.closeSync(file.fd);// 使用循環將Uint8Array轉換為字符串const uint8Array = new Uint8Array(arrayBuffer);let result = '';for (let i = 0; i < uint8Array.length; i++) {result += String.fromCharCode(uint8Array[i]);}this.outputText = result;} catch (error) {console.error(`讀取文件失敗: ${error.message}`);this.outputText = '讀取文件失敗';}}

1.2? 界面代碼

build() {Column({ space: 20 }) {TextInput({ placeholder: '請輸入要保存的內容' }).width('90%').height(60).onChange((value: string) => {this.inputText = value;})Button('寫入文件').width('60%').height(40).onClick(() => {this.writeToFile();})TextInput({ placeholder: '文件內容將顯示在這里', text: this.outputText }).width('90%').height(60)Button('讀取文件').width('60%').height(40).onClick(() => {this.readFromFile();})}.width('100%').height('100%').justifyContent(FlexAlign.Center)}

1.3? \pages\index.ets代碼

// MainAbility.ets
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';@Entry
@Component
struct FileReadWriteExample {@State inputText: string = '';@State outputText: string = '';private context = getContext(this) as common.UIAbilityContext;private filePath: string = '';aboutToAppear() {this.filePath = this.context.filesDir + '/example.txt';console.log(`文件路徑: ${this.filePath}`);}writeToFile() {try {let file = fs.openSync(this.filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);fs.writeSync(file.fd, this.inputText);fs.closeSync(file.fd);this.outputText = '內容已成功寫入文件';console.log('寫入文件成功');} catch (error) {console.error(`寫入文件失敗: ${error.message}`);this.outputText = '寫入文件失敗';}}readFromFile() {try {if (!fs.accessSync(this.filePath)) {this.outputText = '文件不存在';return;}let file = fs.openSync(this.filePath, fs.OpenMode.READ_ONLY);let stat = fs.statSync(this.filePath);let arrayBuffer = new ArrayBuffer(stat.size);fs.readSync(file.fd, arrayBuffer);fs.closeSync(file.fd);// 使用循環將Uint8Array轉換為字符串const uint8Array = new Uint8Array(arrayBuffer);let result = '';for (let i = 0; i < uint8Array.length; i++) {result += String.fromCharCode(uint8Array[i]);}this.outputText = result;} catch (error) {console.error(`讀取文件失敗: ${error.message}`);this.outputText = '讀取文件失敗';}}build() {Column({ space: 20 }) {TextInput({ placeholder: '請輸入要保存的內容' }).width('90%').height(60).onChange((value: string) => {this.inputText = value;})Button('寫入文件').width('60%').height(40).onClick(() => {this.writeToFile();})TextInput({ placeholder: '文件內容將顯示在這里', text: this.outputText }).width('90%').height(60)Button('讀取文件').width('60%').height(40).onClick(() => {this.readFromFile();})}.width('100%').height('100%').justifyContent(FlexAlign.Center)}
}

1.4? 演示

二、首選項讀寫

2.1? 頁面顯示代碼index.ets,實現顯示3個按鈕。

// index.ets
@Entry
@Component
struct Index {build() {Column() {Button('Button 1').margin({ top: 10, bottom: 10 }).onClick(() => {// 通過全局對象調用Ability方法if (globalThis.entryAbility?.btn1) {globalThis.entryAbility.btn1();}}).width('100%')Row()Button('Button 2').margin({ top: 10, bottom: 10 }).onClick(() => {if (globalThis.entryAbility?.btn2) {globalThis.entryAbility.btn2();}}).width('100%')Button('Button 3').margin({ top: 10, bottom: 10 }).onClick(() => {if (globalThis.entryAbility?.btn3) {globalThis.entryAbility.btn3();}}).width('100%')}.width('100%').height('100%')}
}

2.2? UIAbility的代碼EntryAbility.ets,功能包括

初始化Preferences數據存儲

提供三個按鈕操作:

btn1(): 寫入字符串、二進制數據和數字到Preferences

btn2(): 從Preferences讀取并顯示存儲的數據

btn3(): 刪除Preferences中的數據


Preferences操作
代碼中提供了完整的Preferences CRUD操作:

初始化:initPreferences()異步方法

寫入數據:btn1()使用putSync()同步寫入三種類型數據、字符串、二進制數據(Uint8Array)、數字

讀取數據:btn2()使用getSync()同步讀取數據、使用TextDecoder解碼二進制數據

刪除數據:btn3()使用deleteSync()同步刪除數據


Preferences同步/異步操作:

初始化使用異步getPreferences()

數據操作使用同步方法(putSync, getSync, deleteSync)

寫入后調用flushSync()確保數據持久化

以下為代碼

import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';import { BusinessError } from '@kit.BasicServicesKit';import { preferences } from '@kit.ArkData';
import { util } from '@kit.ArkTS';const DOMAIN = 0x0000;
let dataPreferences: preferences.Preferences | null = null;export default class EntryAbility extends UIAbility {// 初始化Preferencesasync initPreferences(): Promise<void> {try {let options: preferences.Options = { name: 'myStore' };dataPreferences = await preferences.getPreferences(this.context, options);} catch (err) {hilog.error(DOMAIN, 'testTag', 'Failed to get preferences. Cause: %{public}s', JSON.stringify(err));}}// 按鈕1:寫入數據btn1(): void {if (!dataPreferences) {console.error('click btn1 Preferences not initialized');return;}try {// 寫入字符串dataPreferences.putSync('string_key', 'Hello ArkTS');// 寫入Uint8Arraylet encoder = new util.TextEncoder();let uInt8Array = encoder.encodeInto("你好,ArkTS");dataPreferences.putSync('binary_key', uInt8Array);// 寫入數字dataPreferences.putSync('number_key', 123);dataPreferences.flushSync();console.info('click btn1 Preferences Data written successfully');} catch (err) {console.error('click btn1 Preferences Failed to write data: ' + JSON.stringify(err));}}// 按鈕2:讀取數據btn2(): void {if (!dataPreferences) {console.error('click btn2 Preferences not initialized');return;}try {// 讀取字符串let stringVal = dataPreferences.getSync('string_key', 'default');console.info('click btn2 Preferences String value: ' + stringVal);// 讀取二進制數據let binaryVal = dataPreferences.getSync('binary_key', new Uint8Array(0));let decoder = new util.TextDecoder('utf-8');let decodedStr = decoder.decode(binaryVal as Uint8Array);console.info('click btn2 Preferences Binary value: ' + decodedStr);// 讀取數字let numberVal = dataPreferences.getSync('number_key', 0);console.info('click btn2 Preferences Number value: ' + numberVal);} catch (err) {console.error('click btn2 Preferences Failed to read data: ' + JSON.stringify(err));}}// 按鈕3:刪除數據btn3(): void {if (!dataPreferences) {console.error('click btn3 Preferences not initialized');return;}try {dataPreferences.deleteSync('string_key');dataPreferences.deleteSync('binary_key');dataPreferences.deleteSync('number_key');console.info('click btn3 Preferences Data deleted successfully');} catch (err) {console.error('click btn3 Preferences Failed to delete data: ' + JSON.stringify(err));}}onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');globalThis.abilityContext = this.context;globalThis.entryAbility = this;// 初始化Preferencesthis.initPreferences();}onWindowStageCreate(windowStage: window.WindowStage): void {// Main window is created, set main page for this abilityhilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');windowStage.loadContent('pages/Index', (err) => {if (err.code) {hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));return;}hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');});/*let options: preferences.Options = { name: 'myStore' };dataPreferences = preferences.getPreferencesSync(this.context, options);if (dataPreferences.hasSync('startup')) {console.info("The key 'startup' is contained.");} else {console.info("The key 'startup' does not contain.");// 此處以此鍵值對不存在時寫入數據為例dataPreferences.putSync('startup', 'auto');// 當字符串有特殊字符時,需要將字符串轉為Uint8Array類型再存儲,長度均不超過16 * 1024 * 1024個字節。//let uInt8Array1 = new util.TextEncoder().encodeInto("~!@#¥%……&*()——+?");let encoder: util.TextEncoder = new util.TextEncoder();let uInt8Array1: Uint8Array = encoder.encodeInto("你好,ArkTS"); // 或 encode()dataPreferences.putSync('uInt8', uInt8Array1);}let val = dataPreferences.getSync('startup', 'default');console.info("The 'startup' value is " + val);// 當獲取的值為帶有特殊字符的字符串時,需要將獲取到的Uint8Array轉換為字符串let uInt8Array2 : preferences.ValueType = dataPreferences.getSync('uInt8', new Uint8Array(0));let textDecoder = util.TextDecoder.create('utf-8');val = textDecoder.decodeToString(uInt8Array2 as Uint8Array);console.info("The 'uInt8' value is " + val);*/}onWindowStageDestroy(): void {// Main window is destroyed, release UI related resourceshilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');}onForeground(): void {// Ability has brought to foregroundhilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');}onBackground(): void {// Ability has back to backgroundhilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');}
}

2.3? 測試效果如下,測試了寫入,讀出,刪除。刪除后再讀出則為空。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/88257.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/88257.shtml
英文地址,請注明出處:http://en.pswp.cn/web/88257.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【Bluedroid】藍牙協議棧控制器能力解析與核心功能配置機制(decode_controller_support)

本文圍繞Bluedroid藍牙協議棧中控制器能力解析與核心功能配置的關鍵代碼展開&#xff0c;詳細闡述藍牙協議棧如何通過解析控制器硬件能力&#xff0c;構建 SCO/eSCO、ACL 數據包類型支持掩碼&#xff0c;配置鏈路策略、安全服務、查詢與掃描模式等核心功能。這些機制確保協議棧…

小架構step系列07:查找日志配置文件

1 概述 日志這里采用logback&#xff0c;其為springboot默認的日志工具。其整體已經被springboot封裝得比較好了&#xff0c;扔個配置文件到classpath里就能夠使用。 但在實際使用中&#xff0c;日志配置文件有可能需要進行改動&#xff0c;比如日志的打印級別&#xff0c;平…

一文講清楚React Hooks

文章目錄一文講清楚React Hooks一、什么是 React Hooks&#xff1f;二、常用基礎 Hooks2.1 useState&#xff1a;狀態管理基本用法特點2.2 useEffect&#xff1a;副作用處理基本用法依賴數組說明2.3 useContext&#xff1a;上下文共享基本用法特點三、其他常用 Hooks3.1 useRed…

Apache http 強制 https

1. 修改一下文件配置 sudo nano /etc/apache2/sites-enabled/000-default.conf<VirtualHost *:80>ServerName hongweizhu.comServerAlias www.hongweizhu.comServerAdmin webmasterlocalhostDocumentRoot /var/www/html# 強制重定向到HTTPSRewriteEngine OnRewriteCond …

【讀代碼】GLM-4.1V-Thinking:開源多模態推理模型的創新實踐

一、基本介紹 1.1 項目背景 GLM-4.1V-Thinking是清華大學KEG實驗室推出的新一代開源視覺語言模型,基于GLM-4-9B-0414基礎模型構建。該項目通過引入"思維范式"和強化學習課程采樣(RLCS)技術,顯著提升了模型在復雜任務中的推理能力。其創新點包括: 64k超長上下文…

從代碼生成到智能運維的革命性變革

AI大模型重塑軟件開發&#xff1a;從代碼生成到智能運維的革命性變革 希望對大家有一定的幫助&#xff0c;進行參考 目錄AI大模型重塑軟件開發&#xff1a;從代碼生成到智能運維的革命性變革 希望對大家有一定的幫助&#xff0c;進行參考一、范式轉移&#xff1a;軟件開發進入&…

豆包編寫Java程序小試

今天下載了一本第四版電氣工程師手冊&#xff0c;非常棒的一本書&#xff0c;在給PDF添加目錄的時候&#xff0c;由于目錄有將近60頁&#xff0c;使用老馬開發的PdgCntEditor有點卡頓&#xff0c;不過補充下&#xff0c;老馬這個PdgCntEditor還是非常好的。所以我決定用Java編一…

SpringBoot整合騰訊云新一代行為驗證碼

一 產品介紹 騰訊云官方介紹鏈接 騰訊云新一代行為驗證碼&#xff08;Captcha&#xff09;&#xff0c;基于十道安全防護策略&#xff0c;為網頁、App、小程序開發者打造立體、全面的人機驗證。在保護注冊登錄、活動秒殺、點贊發帖、數據保護等各大場景下業務安全的同時&…

SenseGlove新一代外骨骼力反饋手套Rembrand來襲!亞毫米級手部動捕+指尖觸覺力采集+5Dof主動力反饋多模態

在遠程機器人操作領域&#xff0c;精準的觸覺感知與靈活的動作控制始終是核心需求。SenseGlove 新推出的 Rembrandt 力反饋外骨骼數據手套&#xff0c;以先進技術為支撐&#xff0c;為遠程操控人形機器人手部提供了無縫解決方案&#xff0c;讓操作更精準、更高效。值得一提的是…

Linux 信號機制:操作系統的“緊急電話”系統

想象一下&#xff0c;你正在電腦前專心工作&#xff0c;突然手機響了——這是一個通知&#xff0c;要求你立即處理一件新事情&#xff08;比如接電話&#xff09;。 Linux 系統中的信號&#xff08;Signal&#xff09;?? 機制&#xff0c;本質上就是操作系統內核或進程之間用…

論文略讀:Prefix-Tuning: Optimizing Continuous Prompts for Generation

2021 ACL固定預訓練LM&#xff0c;為LM添加可訓練&#xff0c;任務特定的前綴這樣就可以為不同任務保存不同的前綴這種前綴可以看成連續可微的soft prompt&#xff0c;相比于離散的token&#xff0c;更好優化&#xff0c;效果更好訓練的時候只需要更新prefix部分的參數&#xf…

CSS基礎選擇器、文本屬性、引入方式及Chorme調試工具

CSS基礎 1.1 CSS簡介 CSS 是層疊樣式表 ( Cascading Style Sheets ) 的簡稱. 有時我們也會稱之為 CSS 樣式表或級聯樣式表。 CSS 是也是一種標記語言 CSS 主要用于設置 HTML 頁面中的文本內容&#xff08;字體、大小、對齊方式等&#xff09;、圖片的外形&#xff08;寬高、邊…

RabbitMQ 高級特性之事務

1. 簡介與 MySQL、Redis 一樣&#xff0c;RabbitMQ 也支持事務。事務中的消息&#xff0c;要么全都發送成功&#xff0c;要么全部發送失敗&#xff0c;不會出現一部分成功一部分失敗的情況。2. 使用事務發送消息spring 中使用 RabbitMQ 開啟事務需要兩步&#xff1a;第一步&…

iframe 的同源限制與反爬機制的沖突

一、事件背景A域名接入了動態防護&#xff08;Bot 防護、反爬蟲機制&#xff09;&#xff0c;同時第三方業務B域名通過內嵌iframe的方式調用了A域名下的一個鏈接。二、動態防護介紹&#xff1a;動態防護&#xff08;也稱為 Bot 防護、反爬蟲機制&#xff09;是網站為了防止自動…

Rust 的 Copy 語義:深入淺出指南

在 Rust 中&#xff0c;Copy 是一個關鍵的特性&#xff0c;它定義了類型的復制行為。理解 Copy 語義對于掌握 Rust 的所有權系統和編寫高效代碼至關重要。一、核心概念&#xff1a;Copy vs Move特性Copy 類型非 Copy 類型 (Move)賦值行為按位復制 (bitwise copy)所有權轉移 (ow…

Qt的信號與槽(二)

Qt的信號與槽&#xff08;二&#xff09;1.自定義槽2.通過圖形化界面來生成自定義槽3.自定義信號3.信號和槽帶參數4.參數數量5.connect函數的設計&#x1f31f;hello&#xff0c;各位讀者大大們你們好呀&#x1f31f;&#x1f31f; &#x1f680;&#x1f680;系列專欄&#xf…

Java研學-MongoDB(三)

三 文檔相關 7 文檔統計查詢① 語法&#xff1a; // 精確統計文檔數 慢 準 dahuang> db.xiaohuang.countDocuments({條件}) 4 // 粗略統計文檔數 快 大致準 dahuang> db.xiaohuang.estimatedDocumentCount({條件}) 4② 例子&#xff1a; // 精確統計文檔數 name為奔波兒灞…

TCP協議格式與連接釋放

TCP報文段格式 TCP雖然是面向字節流的&#xff0c;但TCP傳送帶數據單元確是報文段。TCP報文段分為首部和數據段部分&#xff0c;而TCP的全部功能體現在它在首部中各字段的作用。因此&#xff0c;只有弄清TCP首部各字段的作用才能掌握TCP的工作原理。 TCP報文段首部的前20字節是…

CSS05:結構偽類選擇器和屬性選擇器

結構偽類選擇器 /*ul的第一個子元素*/ ul li:first-child{background: #0af6f6; }/*ul的最后一個子元素*/ ul li:last-child{background: #d27bf3; } /*選中p1&#xff1a;定位到父元素&#xff0c;選擇當前的第一個元素 選擇當前p元素的父級元素&#xff0c;選中父級元素的第…

使用策略模式 + 自動注冊機制來構建旅游點評系統的搜索模塊

? 目標&#xff1a; 搜索模塊支持不同內容類型&#xff08;攻略、達人、游記等&#xff09;每種搜索邏輯用一個策略類表示自動注冊&#xff08;基于注解 Spring 容器&#xff09;新增搜索類型時&#xff0c;只需添加一個類 一個注解&#xff0c;無需改工廠、注冊表等&#x…