import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
import { buffer } from '@kit.ArkTS';
let context = getContext(this) as common.UIAbilityContext; // 获取设备B的UIAbilityContext信息
let pathDir: string = context.distributedFilesDir;
// 获取分布式目录的文件路径
let filePath: string = pathDir + '/test.txt';
try {
// 打开分布式目录下的文件
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
// 定义接收读取数据的缓存
let arrayBuffer = new ArrayBuffer(4096);
// 读取文件的内容,返回值是读取到的字节个数
class Option {
public offset: number = 0;
public length: number = 0;
}
let option = new Option();
option.length = arrayBuffer.byteLength;
let num = fs.readSync(file.fd, arrayBuffer, option);
// 打印读取到的文件数据
let buf = buffer.from(arrayBuffer, 0, num);
console.info('read result: ' + buf.toString());
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`);
}