let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
新建并读写文件: 使用@kit.CoreFileKit中的fileIo模块新建并写入文件:
import { fileIo as fs } from '@kit.CoreFileKit';
function createFile(): void {
let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let writeLen = fs.writeSync(file.fd, "Try to write str.");
console.info("The length of str is: " + writeLen);
fs.closeSync(file);
}
以流的形式读写文件: 建议用流来处理:
import { fileIo as fs } from '@kit.CoreFileKit';
async function readWriteFileWithStream(): Promise<void> {
let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+');
let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+");
let bufSize = 4096;
let readSize = 0;
let buf = new ArrayBuffer(bufSize);
let readLen = await inputStream.read(buf, { offset: readSize, length: bufSize });
readSize += readLen;
while (readLen > 0) {
const writeBuf = readLen < bufSize ? buf.slice(0, readLen) : buf;
await outputStream.write(writeBuf);
let readOptions = { offset: readSize, length: bufSize };
readLen = await inputStream.read(buf, readOptions);
readSize += readLen;
}
inputStream.closeSync();
outputStream.closeSync();
}
获取文件路径:
通过
UIAbilityContext
获取文件路径:新建并读写文件:
使用
@kit.CoreFileKit
中的fileIo
模块新建并写入文件:以流的形式读写文件:
建议用流来处理:
权限管理:
需要在应用的配置文件中声明所需的权限,在调用受权限管控的接口前,使用API(如
checkAccessToken
)来校验当前是否已经授权。 如果用户拒绝了权限请求,需要引导用户到系统设置中打开相应的权限。