积分1621 / 贡献20

提问18答案被采纳65文章40

[经验分享] 文件选择和读取 原创

深开鸿_王石 显示全部楼层 发表于 3 天前

开发DFU需要用到文件选择和读取,特记录下:

1,选文件,用picker可以看系统内的文件

import picker from '@ohos.file.picker';
let documentSelectOptions = new picker.DocumentSelectOptions();
let documentPicker = new picker.DocumentViewPicker();
let that = this;
documentPicker.select(documentSelectOptions).then(async (documentSelectResult: Array<string>) => {
  console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' + JSON.stringify(documentSelectResult));
}

2,读文件,得到的ArrayBuffer就是二进制内容

try {
  console.log(`openSync: ${this.fileSelect}`);

  let file = fs.openSync(this.fileSelect, fs.OpenMode.READ_ONLY);
  console.info(`openReadSync: get fd success. file ${JSON.stringify(file)}`)
  console.info(`openReadSync: get fd success. fd ${JSON.stringify(file.fd)}`)
  let sta = fs.statSync(file.fd);
  console.info(`fstate: ${JSON.stringify(sta)},${sta.size},${sta.ctime}`);
  let buffer = new ArrayBuffer(sta.size);
  let readOut = fs.readSync(file.fd, buffer, {offset:0});
  console.info(`read: ${readOut},${buffer.byteLength}`);
  let uint8b = new Uint8Array(buffer);
  console.info(`buf: ${uint8b[0]},${uint8b[1]},${uint8b[2]},${uint8b[3]}`);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error('fs failed with err: ' + JSON.stringify(err));
}

3,对应权限

ohos.permission.MEDIA_LOCATION
ohos.permission.READ_MEDIA
ohos.permission.WRITE_MEDIA
ohos.permission.FILE_ACCESS_MANAGER

以上代码在4.1 release,5.0.0 上验证过,使用API11

©著作权归作者所有,转载或内容合作请联系作者

您尚未登录,无法参与评论,登录后可以:
参与开源共建问题交流
认同或收藏高质量问答
获取积分成为开源共建先驱

Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

返回顶部