OpenHarmony开发者论坛

标题: 文件选择和读取 [打印本页]

作者: 深开鸿_王石    时间: 2024-11-11 16:30
标题: 文件选择和读取
[md]开发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
[/md]




欢迎光临 OpenHarmony开发者论坛 (https://forums.openharmony.cn/) Powered by Discuz! X3.5