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 運行效果如下

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/469872.html
標籤:其他
