1import StartupTask from '@ohos.app.appstartup.StartupTask'; 2import common from '@ohos.app.ability.common'; 3import fs from '@ohos.file.fs'; 4 5@Sendable 6export default class FileTask extends StartupTask { 7 constructor() { 8 super(); 9 } 10 11 async init(context: common.AbilityStageContext) { 12 let filesDir = context.filesDir; 13 this.createFile(filesDir); 14 } 15 16 createFile(filesDir: string) { 17 let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 18 fs.writeSync(srcFile.fd, 'test StartupTask_003 file write data'); 19 let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 20 // 读取源文件内容并写入至目的文件 21 let bufSize = 4096; 22 let readSize = 0; 23 let buf = new ArrayBuffer(bufSize); 24 25 class Option { 26 public offset: number = 0; 27 public length: number = bufSize; 28 } 29 30 let option = new Option(); 31 option.offset = readSize; 32 let readLen = fs.readSync(srcFile.fd, buf, option); 33 while (readLen > 0) { 34 readSize += readLen; 35 fs.writeSync(destFile.fd, buf, { length: readLen }); 36 option.offset = readSize; 37 readLen = fs.readSync(srcFile.fd, buf, option); 38 } 39 // 关闭文件 40 fs.closeSync(srcFile); 41 fs.closeSync(destFile); 42 } 43 44 45 onDependencyCompleted(dependence: string, result: Object): void { 46 } 47} 48 49