【Harmony OS】【ARK UI】ets实现文件读写操作
1. 准备阶段
关于该功能的实现我们需要学习以下的资料:
1.1 【ARKUI】ets怎么实现文件操作
1.2 文件管理
1.3 Ability上下文
2. demo 实现
2.1 文件路径读取
参考 context.getFilesDir 来进行获取文件路径,代码如下
private getCacheDir(){
var context = ability_featureAbility.getContext();
context.getFilesDir()
.then((data) => {
console.log('File directory obtained. Data:' + data);
this.path=data;
}).catch((error) => {
console.error('Failed to obtain the file directory. Cause: ' + error.message);
})
}
2.2 文件写入操作
参考 fileio.createStream 和 write 和 flush 相关 Api,资料和代码如下
实现代码
private writeFile(){
let ss= fileio.createStreamSync(this.path+"/111.txt", "w+");
let num = ss.write("你好 2022",null);
ss.flush();
console.log("写入成功");
}
2.3 文件读取文件操作
想实现文件的读取,需要参考 read 的 Api,资料和代码如下:
代码如下:
private readFile(){
let ss = fileio.createStreamSync(this.path+"/111.txt", "r+");
ss.read(new ArrayBuffer(4096),null,function (err, readOut) {
if (!err) {
let encodedString = String.fromCodePoint.apply(null, new Uint8Array(readOut.buffer));
let decodedString = decodeURIComponent(escape(encodedString));//没有这一步中文会乱码
console.log("读取文件内容:"+decodedString);
}
});
}
3. 运行效果
3.1 全部代码如下
import fileio from '@ohos.fileio';
import ability_featureAbility from '@ohos.ability.featureAbility';
@Entry
@Component
struct MyFileStream {
@State path:string="";
private getFilesDirNew(){
var context = ability_featureAbility.getContext();
context.getFilesDir()
.then((data) => {
console.log('获取文件路径成功' + data);
this.path=data;
}).catch((error) => {
console.error('Failed to obtain the file directory. Cause: ' + error.message);
})
}
private writeFile(){
let ss= fileio.createStreamSync(this.path+"/111.txt", "w+");
let num = ss.write("你好 2022",null);
ss.flush();
console.log("写入成功")
}
private readFile(){
let ss = fileio.createStreamSync(this.path+"/111.txt", "r+");
ss.read(new ArrayBuffer(4096),null,function (err, readOut) {
if (!err) {
let encodedString = String.fromCodePoint.apply(null, new Uint8Array(readOut.buffer));
let decodedString = decodeURIComponent(escape(encodedString));//没有这一步中文会乱码
console.log("读取文件内容:"+decodedString);
}
});
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('获取文件路径')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.backgroundColor(Color.Red)
.onClick(this.getFilesDirNew.bind(this))
Text('写入文字')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.backgroundColor(Color.White)
.onClick(this.writeFile.bind(this))
Text('读取文字')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.backgroundColor(Color.Red)
.onClick(this.readFile.bind(this))
}
.width('100%')
.height('100%')
}
}
3.2 运行效果如下