文章的目的为了记录使用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…