当前位置: 首页> 文旅> 美景 > 网络架构有哪几层_收录批量查询_博客网_30条新闻摘抄

网络架构有哪几层_收录批量查询_博客网_30条新闻摘抄

时间:2025/7/9 21:13:26来源:https://blog.csdn.net/qq_52940467/article/details/144702620 浏览次数:0次
网络架构有哪几层_收录批量查询_博客网_30条新闻摘抄

【鸿蒙笔试题】将内容写入文件,读取内容到文本上

文章目录

  • 【鸿蒙笔试题】将内容写入文件,读取内容到文本上
  • 前言
  • 一、实现步骤
    • 1.写入数据
    • 2.读取数据
    • 3.完整代码
    • 4.存储位置及打开方式


前言

本文主要展示了鸿蒙的文件使用,如何简单实现将内容写入文件,并从文件读取内容到界面上,效果如下:
在这里插入图片描述

一、实现步骤

1.写入数据

  writeText() {//fileIo.accessSync检查文件if (fileIo.accessSync(this.filePath)) {//如果存在文件则删除文件fileIo.rmdirSync(this.filePath)}const file = fileIo.openSync(this.filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE)const str = 'hello cc'fileIo.writeSync(file.fd, str)fileIo.closeSync(file.fd)promptAction.showToast({ message: '写入文件成功' })}

2.读取数据

通过fileIo.readTextSync方法可以直接读取文件内容,返回一个字符串

  readText() {this.content = fileIo.readTextSync(this.filePath)AlertDialog.show({ message: this.content, alignment: DialogAlignment.Center })}

3.完整代码

import { fileIo } from '@kit.CoreFileKit'
import { promptAction } from '@kit.ArkUI'@Entry
@Component
struct Index {
//定义一个状态变量@State content: string = ''filePath = getContext(this).cacheDir + '/text.txt'writeText() {if (fileIo.accessSync(this.filePath)) {//如果存在文件则删除文件fileIo.rmdirSync(this.filePath)}const file = fileIo.openSync(this.filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE)const str = 'hello cc'fileIo.writeSync(file.fd, str)fileIo.closeSync(file.fd)promptAction.showToast({ message: '写入文件成功' })}readText() {this.content = fileIo.readTextSync(this.filePath)AlertDialog.show({ message: this.content, alignment: DialogAlignment.Center })}build() {Column({ space: 20 }) {Button('写入文件').width(100).backgroundColor(Color.Orange).onClick(() => {this.writeText()})Button('读取文件').width(100).backgroundColor(Color.Orange).onClick(() => {this.readText()})Text(this.content).fontSize(20).textAlign(TextAlign.Center).width(200).height(200).borderRadius(10).backgroundColor(Color.Blue)}.width('100%').justifyContent(FlexAlign.Center)}
}

4.存储位置及打开方式

点击右下角Device File Browser,按照路径打开,本文介绍的是存储到沙箱路径。注意包名称去app.json5查找,找到对应的项目路径。注意,以下为模拟器演示路径。
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

关键字:网络架构有哪几层_收录批量查询_博客网_30条新闻摘抄

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: