【鸿蒙笔试题】将内容写入文件,读取内容到文本上
文章目录
- 【鸿蒙笔试题】将内容写入文件,读取内容到文本上
- 前言
- 一、实现步骤
- 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查找,找到对应的项目路径。注意,以下为模拟器演示路径。