代码拉取完成,页面将自动刷新
文件拷贝是应用开发中的一个常见场景,通常有两种方式,一是直接读写文件的全部内容,二是使用buffer多次读写。前者的优点在于使用简单,但是在大文件场景下,内存占用较高,影响应用性能;后者的优点在于内存占用较小,但是编程稍显复杂。本例将展示如何使用buffer来将大文件的rawfile复制到应用沙箱。
使用说明
let data: resourceManager.RawFileDescriptor = this.context.resourceManager.getRawFdSync(this.fileName);
let targetPath: string = this.context.filesDir + "/" + this.fileName;
let destFile: fs.File = fs.openSync(targetPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
let buffSize: number = BigFileCopyConstants.BUFF_SIZE;
let buffer: ArrayBuffer = new ArrayBuffer(buffSize);
let off: number = 0; // 记录读取位置的偏移(相较于文件起始偏移)
let len: number = 0; // 本次读取内容的实际长度
let readedLen: number = 0; // 记录已读文件长度
while (len = fs.readSync(data.fd, buffer, { offset: data.offset + off, length: buffSize })) {
readedLen += len;
fs.writeSync(destFile.fd, buffer, { offset: off, length: len });
off = off + len;
if ((data.length - readedLen) < buffSize) {
buffSize = data.length - readedLen;
}
}
Image(BigFileCopyConstants.SANDBOX_PREFIX + this.targetFilePath)
不涉及
bigfilecopy // har类型
|---constants
| |---BigFileCopyConstants // 常量
|---view
| |---BigFileCopyView.ets // 视图层-文件复制页面
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。