ets怎么实现文件操作?
关于文件操作的我们可以学习HarmonyOS文件管理和Ability上下文 这两篇文档,我这边实现”文件路径读取”、“文件写入”“文件读取”,“运行效果”四个方面实现,具体操作如下
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. 文件写入
参考fileio.openSync的api,实现代码如下
private writeFiles(){
let fd = fileio.openSync(this.path+"/111.txt", 0o102, 0o666);
fileio.write(fd, "你好 2022", function (err, bytesWritten) {
if (!err) {
console.log("写入成功")
}
});
}
3. 文件读取
参考 fileio.read这个api ,代码如下
private ReadFile(){
let Filepath = this.path+"/111.txt";
let fd = fileio.openSync(Filepath, 0o2);
let buf = new ArrayBuffer(4096);
fileio.read(fd, buf, function (err, readOut) {
if (!err) {
let encodedString = String.fromCodePoint.apply(null, new Uint8Array(readOut.buffer));
let decodedString = decodeURIComponent(escape(encodedString));//没有这一步中文会乱码
console.log("读取文件内容"+decodedString);
}
});
}
4. 运行效果
全部代码如下
import fileio from '@ohos.fileio';
import ability_featureAbility from '@ohos.ability.featureAbility';
struct NewmyFileTwo {
path:string="";
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);
})
}
private writeFiles(){
let fd = fileio.openSync(this.path+"/111.txt", 0o102, 0o666);
fileio.write(fd, "你好 2022", function (err, bytesWritten) {
if (!err) {
console.log("写入成功")
}
});
}
private ReadFile(){
let Filepath = this.path+"/111.txt";
let fd = fileio.openSync(Filepath, 0o2);
let buf = new ArrayBuffer(4096);
fileio.read(fd, buf, function (err, readOut) {
if (!err) {
let encodedString = String.fromCodePoint.apply(null, new Uint8Array(readOut.buffer));
let decodedString = decodeURIComponent(escape(encodedString));//没有这一步中文会乱码
console.log("读取文件内容"+decodedString);
}
});
}
private getFilesDirNew(){
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);
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('获取文件目录')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(this.getFilesDirNew.bind(this));
Text('写文件 你好 2022 到文件中')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.backgroundColor(Color.Red)
.onClick(this.writeFiles.bind(this));
Text('读文件内容')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.backgroundColor(Color.White)
.onClick(this.ReadFile.bind(this));
}
.width('100%')
.height('100%')
}
}
效果图如下: