参考以下demo。首先通过Picker选择文件保存地址,再用uri保存该地址,再使用ohos.file.fs对文件进行读写。同理,你可以先获取文件保存地址后,再将数据存入。
import { common } from '@kit.AbilityKit';
import { picker } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo as fs } from '@kit.CoreFileKit';
@Entry
@Component
struct Picker {
@State message1: string = '点我新建文件';
@State message2: string = '点我写入文件'
@State uri: string = ''
build() {
Row() {
Column() {
Text(this.message1)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let context = getContext(this) as common.Context; // 请确保getContext(this)返回结果为UIAbilityContext
try {
let documentSaveOptions = new picker.DocumentSaveOptions();
documentSaveOptions.newFileNames = ['DocumentViewPicker01.txt'];
let documentPicker = new picker.DocumentViewPicker(context);
documentPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
this.uri = documentSaveResult[0];
console.info('DocumentViewPicker.save successfully, documentSaveResult uri: ' + this.uri);
}).catch((err: BusinessError) => {
console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
});
let file = fs.openSync(this.uri, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd);
let writeLen: number = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err));
}
})
.margin({bottom:23})
Text(this.message2)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let file = fs.openSync(this.uri, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd);
let writeLen: number = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
})
}
.width('100%')
}
.height('100%')
}
}