1# @ohos.file.fs (文件管理) 2 3该模块为基础文件操作API,提供基础文件操作能力,包括文件基本管理、文件目录管理、文件信息统计、文件流式读写等常用功能。 4 5> **说明:** 6> 7> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 8 9## 导入模块 10 11```ts 12import { fileIo as fs } from '@kit.CoreFileKit'; 13``` 14 15## 使用说明 16 17使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径,获取方式及其接口用法请参考: 18 19 ```ts 20 import { UIAbility } from '@kit.AbilityKit'; 21 import { window } from '@kit.ArkUI'; 22 23 export default class EntryAbility extends UIAbility { 24 onWindowStageCreate(windowStage: window.WindowStage) { 25 let context = this.context; 26 let pathDir = context.filesDir; 27 } 28 } 29 ``` 30 31使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径。表示沙箱路径的字符串称为path,获取方式及其接口用法请参考:[应用上下文Context-获取应用文件路径](../../application-models/application-context-stage.md#获取应用文件路径)。 32将指向资源的字符串称为URI。对于只支持path作为入参的接口可使用构造fileUri对象并获取其path属性的方式将URI转换为path,然后使用文件接口。URI定义解及其转换方式请参考:[文件URI](../../../application-dev/reference/apis-core-file-kit/js-apis-file-fileuri.md)。 33 34## fs.stat 35 36stat(file: string | number): Promise<Stat> 37 38获取文件详细属性信息,使用Promise异步返回。 39 40**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 41 42**系统能力**:SystemCapability.FileManagement.File.FileIO 43 44**参数:** 45 46| 参数名 | 类型 | 必填 | 说明 | 47| ------ | ------ | ---- | -------------------------- | 48| file | string \| number | 是 | 文件应用沙箱路径path或已打开的文件描述符fd。 | 49 50**返回值:** 51 52 | 类型 | 说明 | 53 | ---------------------------- | ---------- | 54 | Promise<[Stat](#stat)> | Promise对象。返回文件的具体信息。 | 55 56**错误码:** 57 58接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 59 60**示例:** 61 62 ```ts 63 import { BusinessError } from '@kit.BasicServicesKit'; 64 let filePath = pathDir + "/test.txt"; 65 fs.stat(filePath).then((stat: fs.Stat) => { 66 console.info("get file info succeed, the size of file is " + stat.size); 67 }).catch((err: BusinessError) => { 68 console.error("get file info failed with error message: " + err.message + ", error code: " + err.code); 69 }); 70 ``` 71 72## fs.stat 73 74stat(file: string | number, callback: AsyncCallback<Stat>): void 75 76获取文件详细属性信息,使用callback异步回调。 77 78**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 79 80**系统能力**:SystemCapability.FileManagement.File.FileIO 81 82**参数:** 83 84| 参数名 | 类型 | 必填 | 说明 | 85| -------- | ---------------------------------- | ---- | ------------------------------ | 86| file | string \| number | 是 | 文件应用沙箱路径path或已打开的文件描述符fd。 | 87| callback | AsyncCallback<[Stat](#stat)> | 是 | 异步获取文件的信息之后的回调。 | 88 89**错误码:** 90 91接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 92 93**示例:** 94 95 ```ts 96 import { BusinessError } from '@kit.BasicServicesKit'; 97 fs.stat(pathDir, (err: BusinessError, stat: fs.Stat) => { 98 if (err) { 99 console.error("get file info failed with error message: " + err.message + ", error code: " + err.code); 100 } else { 101 console.info("get file info succeed, the size of file is " + stat.size); 102 } 103 }); 104 ``` 105 106## fs.statSync 107 108statSync(file: string | number): Stat 109 110以同步方法获取文件详细属性信息。 111 112**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 113 114**系统能力**:SystemCapability.FileManagement.File.FileIO 115 116**参数:** 117 118| 参数名 | 类型 | 必填 | 说明 | 119| ------ | ------ | ---- | -------------------------- | 120| file | string \| number | 是 | 文件应用沙箱路径path或已打开的文件描述符fd。 | 121 122**返回值:** 123 124 | 类型 | 说明 | 125 | ------------- | ---------- | 126 | [Stat](#stat) | 表示文件的具体信息。 | 127 128**错误码:** 129 130接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 131 132**示例:** 133 134 ```ts 135 let stat = fs.statSync(pathDir); 136 console.info("get file info succeed, the size of file is " + stat.size); 137 ``` 138 139## fs.access 140 141access(path: string, mode?: AccessModeType): Promise<boolean> 142 143检查文件或目录是否存在,或校验操作权限,使用Promise异步返回。 144 145**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 146 147**系统能力**:SystemCapability.FileManagement.File.FileIO 148 149**参数:** 150 151| 参数名 | 类型 | 必填 | 说明 | 152| ------ | ------ | ---- | ------------------------------------------------------------ | 153| path | string | 是 | 文件应用沙箱路径。 | 154| mode<sup>12+</sup> | [AccessModeType](#accessmodetype12) | 否 | 文件校验的权限。| 155 156**返回值:** 157 158 | 类型 | 说明 | 159 | ------------------- | ---------------------------- | 160 | Promise<boolean> | Promise对象。返回布尔值,表示文件是否存在。 | 161 162**错误码:** 163 164接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 165 166| 错误码ID | 错误信息 | 167| ---------------------------- | ---------- | 168| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 169| 13900020 | 非法参数值。 | 170 171**示例:** 172 173 ```ts 174 import { BusinessError } from '@kit.BasicServicesKit'; 175 let filePath = pathDir + "/test.txt"; 176 fs.access(filePath).then((res: boolean) => { 177 if (res) { 178 console.info("file exists"); 179 } else { 180 console.info("file not exists"); 181 } 182 }).catch((err: BusinessError) => { 183 console.error("access failed with error message: " + err.message + ", error code: " + err.code); 184 }); 185 ``` 186 187## fs.access 188 189access(path: string, mode: AccessModeType, flag: AccessFlagType): Promise<boolean> 190 191检查文件或目录是否在本地,或校验操作权限,使用Promise异步返回。如果文件在云端,或者其它分布式设备上,返回false。 192 193**系统能力**:SystemCapability.FileManagement.File.FileIO 194 195**参数:** 196 197| 参数名 | 类型 | 必填 | 说明 | 198| ------ | ------ | ---- | ------------------------------------------------------------ | 199| path | string | 是 | 文件应用沙箱路径。 | 200| mode<sup>12+</sup> | [AccessModeType](#accessmodetype12) | 是 | 文件校验的权限。| 201| flag<sup>12+</sup> | [AccessFlagType](#accessflagtype12) | 是| 文件校验的位置。 | 202 203**返回值:** 204 205 | 类型 | 说明 | 206 | ------------------- | ---------------------------- | 207 | Promise<boolean> | Promise对象。返回布尔值。true:表示文件存在本地且具有相关权限;false:表示文件不存在本地或不具有相关权限。 | 208 209**错误码:** 210 211接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 212 213| 错误码ID | 错误信息 | 214| ---------------------------- | ---------- | 215| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 216| 13900020 | 非法参数值。 | 217 218**示例:** 219 220 ```ts 221 import { BusinessError } from '@kit.BasicServicesKit'; 222 let filePath = pathDir + "/test.txt"; 223 fs.access(filePath, fs.AccessModeType.EXIST, fs.AccessFlagType.LOCAL).then((res: boolean) => { 224 if (res) { 225 console.info("file exists"); 226 } else { 227 console.info("file not exists"); 228 } 229 }).catch((err: BusinessError) => { 230 console.error("access failed with error message: " + err.message + ", error code: " + err.code); 231 }); 232 ``` 233 234## fs.access 235 236access(path: string, callback: AsyncCallback<boolean>): void 237 238检查文件或目录是否存在,使用callback异步回调。 239 240**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 241 242**系统能力**:SystemCapability.FileManagement.File.FileIO 243 244**参数:** 245 246| 参数名 | 类型 | 必填 | 说明 | 247| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 248| path | string | 是 | 文件应用沙箱路径。 | 249| callback | AsyncCallback<boolean> | 是 | 异步检查文件是否存在的回调。如果存在,回调返回true;否则返回false。 | 250 251**错误码:** 252 253接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 254 255| 错误码ID | 错误信息 | 256| ---------------------------- | ---------- | 257| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 258| 13900020 | 非法参数值。| 259 260**示例:** 261 262 ```ts 263 import { BusinessError } from '@kit.BasicServicesKit'; 264 let filePath = pathDir + "/test.txt"; 265 fs.access(filePath, (err: BusinessError, res: boolean) => { 266 if (err) { 267 console.error("access failed with error message: " + err.message + ", error code: " + err.code); 268 } else { 269 if (res) { 270 console.info("file exists"); 271 } else { 272 console.info("file not exists"); 273 } 274 } 275 }); 276 ``` 277 278## fs.accessSync 279 280accessSync(path: string, mode?: AccessModeType): boolean 281 282以同步方法检查文件或目录是否存在,或校验操作权限。 283 284**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 285 286**系统能力**:SystemCapability.FileManagement.File.FileIO 287 288**参数:** 289 290| 参数名 | 类型 | 必填 | 说明 | 291| ------ | ------ | ---- | ------------------------------------------------------------ | 292| path | string | 是 | 文件应用沙箱路径。 | 293| mode<sup>12+</sup> | [AccessModeType](#accessmodetype12) | 否 | 文件校验的权限。 | 294 295**返回值:** 296 297 | 类型 | 说明 | 298 | ------------------- | ---------------------------- | 299 | boolean | 返回true,表示文件存在;返回false,表示文件不存在。 | 300 301**错误码:** 302 303接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 304 305| 错误码ID | 错误信息 | 306| ---------------------------- | ---------- | 307| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 308| 13900020 | 非法参数值。 | 309 310**示例:** 311 312 ```ts 313 import { BusinessError } from '@kit.BasicServicesKit'; 314 let filePath = pathDir + "/test.txt"; 315 try { 316 let res = fs.accessSync(filePath); 317 if (res) { 318 console.info("file exists"); 319 } else { 320 console.info("file not exists"); 321 } 322 } catch(error) { 323 let err: BusinessError = error as BusinessError; 324 console.error("accessSync failed with error message: " + err.message + ", error code: " + err.code); 325 } 326 ``` 327 328## fs.accessSync 329 330accessSync(path: string, mode: AccessModeType, flag: AccessFlagType): boolean 331 332以同步方法检查文件或目录是否在本地,或校验操作权限。如果文件在云端,或者其它分布式设备上,返回false。 333 334**系统能力**:SystemCapability.FileManagement.File.FileIO 335 336**参数:** 337 338| 参数名 | 类型 | 必填 | 说明 | 339| ------ | ------ | ---- | ------------------------------------------------------------ | 340| path | string | 是 | 文件应用沙箱路径。 | 341| mode<sup>12+</sup> | [AccessModeType](#accessmodetype12) | 是 | 文件校验的权限。| 342| flag<sup>12+</sup> | [AccessFlagType](#accessflagtype12) | 是 | 文件校验的位置。 | 343 344**返回值:** 345 346 | 类型 | 说明 | 347 | ------------------- | ---------------------------- | 348 | boolean | 返回true,表示文件存在本地且具有相关权限;返回false,表示文件不存在本地或不具有相关权限。 | 349 350**错误码:** 351 352接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 353 354| 错误码ID | 错误信息 | 355| ---------------------------- | ---------- | 356| 401 | 1. 未指定必须的参数;2. 参数类型与接口定义不匹配。 | 357| 13900020 | 非法参数值。 | 358 359**示例:** 360 361 ```ts 362 import { BusinessError } from '@kit.BasicServicesKit'; 363 let filePath = pathDir + "/test.txt"; 364 try { 365 let res = fs.accessSync(filePath, fs.AccessModeType.EXIST, fs.AccessFlagType.LOCAL); 366 if (res) { 367 console.info("file exists"); 368 } else { 369 console.info("file not exists"); 370 } 371 } catch(error) { 372 let err: BusinessError = error as BusinessError; 373 console.error("accessSync failed with error message: " + err.message + ", error code: " + err.code); 374 } 375 ``` 376 377## fs.close 378 379close(file: number | File): Promise<void> 380 381关闭文件,使用Promise异步返回。 382 383**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 384 385**系统能力**:SystemCapability.FileManagement.File.FileIO 386 387**参数:** 388 389 | 参数名 | 类型 | 必填 | 说明 | 390 | ---- | ------ | ---- | ------------ | 391 | file | number \| [File](#file) | 是 | 已打开的File对象或已打开的文件描述符fd。关闭后file对象或文件描述符不再具备实际意义,不可再用于进行读写等操作。 | 392 393**返回值:** 394 395 | 类型 | 说明 | 396 | ------------------- | ---------------------------- | 397 | Promise<void> | Promise对象。无返回值。 | 398 399**错误码:** 400 401接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 402 403**示例:** 404 405 ```ts 406 import { BusinessError } from '@kit.BasicServicesKit'; 407 let filePath = pathDir + "/test.txt"; 408 let file = fs.openSync(filePath); 409 fs.close(file).then(() => { 410 console.info("close file succeed"); 411 }).catch((err: BusinessError) => { 412 console.error("close file failed with error message: " + err.message + ", error code: " + err.code); 413 }); 414 ``` 415 416## fs.close 417 418close(file: number | File, callback: AsyncCallback<void>): void 419 420关闭文件,使用callback异步回调。 421 422**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 423 424**系统能力**:SystemCapability.FileManagement.File.FileIO 425 426**参数:** 427 428 | 参数名 | 类型 | 必填 | 说明 | 429 | -------- | ------------------------- | ---- | ------------ | 430 | file | number \| [File](#file) | 是 | 已打开的File对象或已打开的文件描述符fd。关闭后file对象或文件描述符不再具备实际意义,不可再用于进行读写等操作。 | 431 | callback | AsyncCallback<void> | 是 | 异步关闭文件之后的回调。 | 432 433**错误码:** 434 435接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 436 437**示例:** 438 439 ```ts 440 import { BusinessError } from '@kit.BasicServicesKit'; 441 let filePath = pathDir + "/test.txt"; 442 let file = fs.openSync(filePath); 443 fs.close(file, (err: BusinessError) => { 444 if (err) { 445 console.error("close file failed with error message: " + err.message + ", error code: " + err.code); 446 } else { 447 console.info("close file succeed"); 448 } 449 }); 450 ``` 451 452## fs.closeSync 453 454closeSync(file: number | File): void 455 456以同步方法关闭文件。 457 458**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 459 460**系统能力**:SystemCapability.FileManagement.File.FileIO 461 462**参数:** 463 464 | 参数名 | 类型 | 必填 | 说明 | 465 | ---- | ------ | ---- | ------------ | 466 | file | number \| [File](#file) | 是 | 已打开的File对象或已打开的文件描述符fd。关闭后file对象或文件描述符不再具备实际意义,不可再用于进行读写等操作。 | 467 468**错误码:** 469 470接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 471 472**示例:** 473 474 ```ts 475 let filePath = pathDir + "/test.txt"; 476 let file = fs.openSync(filePath); 477 fs.closeSync(file); 478 ``` 479 480## fs.copy<sup>11+</sup> 481 482copy(srcUri: string, destUri: string, options?: CopyOptions): Promise\<void> 483 484拷贝文件或者目录,使用Promise异步返回。 485 486支持跨设备拷贝。强制覆盖拷贝。入参支持文件或目录URI。\n 487跨端拷贝时,限制同时最多存在10个拷贝任务;单次拷贝的文件数量不得超过500个。 488 489**系统能力**:SystemCapability.FileManagement.File.FileIO 490 491**参数:** 492 493 | 参数名 | 类型 | 必填 | 说明 | 494 | ---- | -------------------------- | ---- | ---------------------------------------- | 495 | srcUri | string | 是 | 待复制文件或目录的uri。 | 496 | destUri | string | 是 | 目标文件或目录的uri。 | 497 | options | [CopyOptions](#copyoptions11)| 否| options中提供拷贝进度回调。| 498 499**返回值:** 500 501 | 类型 | 说明 | 502 | ------------------- | ---------------------------- | 503 | Promise\<void> | Promise对象。无返回值。 | 504 505**错误码:** 506 507接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 508 509**示例:** 510 511```ts 512import { fileIo as fs } from '@kit.CoreFileKit'; 513import { BusinessError } from '@kit.BasicServicesKit'; 514import { fileUri } from '@kit.CoreFileKit'; 515 516let srcDirPathLocal: string = pathDir + "/src"; 517let dstDirPathLocal: string = pathDir + "/dest"; 518 519let srcDirUriLocal: string = fileUri.getUriFromPath(srcDirPathLocal); 520let dstDirUriLocal: string = fileUri.getUriFromPath(dstDirPathLocal); 521 522let progressListener: fs.ProgressListener = (progress: fs.Progress) => { 523 console.info(`progressSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`); 524}; 525let copyoption: fs.CopyOptions = { 526 "progressListener" : progressListener 527} 528try { 529 fs.copy(srcDirUriLocal, dstDirUriLocal, copyoption).then(()=>{ 530 console.info("Succeeded in copying. "); 531 }).catch((err: BusinessError)=>{ 532 console.error(`Failed to copy: ${JSON.stringify(err)}`); 533 }) 534} catch(err) { 535 console.error(`Failed to copy: ${JSON.stringify(err)}`); 536} 537``` 538 539## fs.copy<sup>11+</sup> 540 541copy(srcUri: string, destUri: string, callback: AsyncCallback\<void>): void 542 543拷贝文件或者目录,使用callback异步回调。 544 545支持跨设备拷贝。强制覆盖拷贝。入参支持文件或目录URI。\n 546跨端拷贝时,限制同时最多存在10个拷贝任务;单次拷贝的文件数量不得超过500个。 547 548**系统能力**:SystemCapability.FileManagement.File.FileIO 549 550**参数:** 551 552 | 参数名 | 类型 | 必填 | 说明 | 553 | ---- | ------------------ | ---- | ----------------------------| 554 | srcUri | string | 是 | 待复制文件或目录的uri。 | 555 | destUri | string | 是 | 目标文件或目录的uri。 | 556 | callback | AsyncCallback\<void>| 是| 异步拷贝之后的回调。| 557 558**错误码:** 559 560接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 561 562**示例:** 563 564```ts 565import { BusinessError } from '@kit.BasicServicesKit'; 566import { fileUri } from '@kit.CoreFileKit'; 567 568let srcDirPathLocal: string = pathDir + "/src"; 569let dstDirPathLocal: string = pathDir + "/dest"; 570 571let srcDirUriLocal: string = fileUri.getUriFromPath(srcDirPathLocal); 572let dstDirUriLocal: string = fileUri.getUriFromPath(dstDirPathLocal); 573 574try { 575 fs.copy(srcDirUriLocal, dstDirUriLocal, (err: BusinessError) => { 576 if (err) { 577 console.error(`Failed to copy: ${JSON.stringify(err)}`); 578 return; 579 } 580 console.info("Succeeded in copying. "); 581 }) 582} catch(err) { 583 console.error(`Failed to copy: ${JSON.stringify(err)}`); 584} 585``` 586 587## fs.copy<sup>11+</sup> 588 589copy(srcUri: string, destUri: string, options: CopyOptions, callback: AsyncCallback\<void>): void 590 591拷贝文件或者目录,使用callback异步回调。 592 593支持跨设备拷贝。强制覆盖拷贝。入参支持文件或目录URI。\n 594跨端拷贝时,限制同时最多存在10个拷贝任务;单次拷贝的文件数量不得超过500个。 595 596**系统能力**:SystemCapability.FileManagement.File.FileIO 597 598**参数:** 599 600 | 参数名 | 类型 | 必填 | 说明 | 601 | ---- | -------------------------- | ---- | ---------------------------------------- | 602 | srcUri | string | 是 | 待复制文件或目录的uri。 | 603 | destUri | string | 是 | 目标文件或目录的uri。 | 604 | options | [CopyOptions](#copyoptions11) |是| 拷贝进度回调。 | 605 | callback | AsyncCallback\<void>| 是| 异步拷贝之后的回调。| 606 607**错误码:** 608 609接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 610 611**示例:** 612 613```ts 614import { fileIo as fs } from '@kit.CoreFileKit'; 615import { BusinessError } from '@kit.BasicServicesKit'; 616import { fileUri } from '@kit.CoreFileKit'; 617 618let srcDirPathLocal: string = pathDir + "/src"; 619let dstDirPathLocal: string = pathDir + "/dest"; 620 621let srcDirUriLocal: string = fileUri.getUriFromPath(srcDirPathLocal); 622let dstDirUriLocal: string = fileUri.getUriFromPath(dstDirPathLocal); 623 624try { 625 let progressListener: fs.ProgressListener = (progress: fs.Progress) => { 626 console.info(`progressSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`); 627 }; 628 let copyoption: fs.CopyOptions = { 629 "progressListener" : progressListener 630 } 631 fs.copy(srcDirUriLocal, dstDirUriLocal, copyoption, (err: BusinessError) => { 632 if (err) { 633 console.error(`Failed to copy: ${JSON.stringify(err)}`); 634 return; 635 } 636 console.info("Succeeded in copying. "); 637 }) 638} catch(err) { 639 console.error(`Failed to copy: ${JSON.stringify(err)}`); 640} 641``` 642 643## fs.copyFile 644 645copyFile(src: string | number, dest: string | number, mode?: number): Promise<void> 646 647复制文件,使用Promise异步返回。 648 649**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 650 651**系统能力**:SystemCapability.FileManagement.File.FileIO 652 653**参数:** 654 655 | 参数名 | 类型 | 必填 | 说明 | 656 | ---- | -------------------------- | ---- | ---------------------------------------- | 657 | src | string \| number | 是 | 待复制文件的路径或待复制文件的文件描述符。 | 658 | dest | string \| number | 是 | 目标文件路径或目标文件的文件描述符。 | 659 | mode | number | 否 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。<br/>0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | 660 661**返回值:** 662 663 | 类型 | 说明 | 664 | ------------------- | ---------------------------- | 665 | Promise<void> | Promise对象。无返回值。 | 666 667**错误码:** 668 669接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 670 671**示例:** 672 673 ```ts 674 import { BusinessError } from '@kit.BasicServicesKit'; 675 let srcPath = pathDir + "/srcDir/test.txt"; 676 let dstPath = pathDir + "/dstDir/test.txt"; 677 fs.copyFile(srcPath, dstPath, 0).then(() => { 678 console.info("copy file succeed"); 679 }).catch((err: BusinessError) => { 680 console.error("copy file failed with error message: " + err.message + ", error code: " + err.code); 681 }); 682 ``` 683 684## fs.copyFile 685 686copyFile(src: string | number, dest: string | number, mode: number, callback: AsyncCallback<void>): void 687 688复制文件,可设置覆盖文件的方式,使用callback异步回调。 689 690**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 691 692**系统能力**:SystemCapability.FileManagement.File.FileIO 693 694**参数:** 695 696 | 参数名 | 类型 | 必填 | 说明 | 697 | -------- | -------------------------- | ---- | ---------------------------------------- | 698 | src | string \| number | 是 | 待复制文件的路径或待复制文件的文件描述符。 | 699 | dest | string \| number | 是 | 目标文件路径或目标文件的文件描述符。 | 700 | mode | number | 是 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。<br/>0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | 701 | callback | AsyncCallback<void> | 是 | 异步复制文件之后的回调。 | 702 703**错误码:** 704 705接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 706 707**示例:** 708 709 ```ts 710 import { BusinessError } from '@kit.BasicServicesKit'; 711 let srcPath = pathDir + "/srcDir/test.txt"; 712 let dstPath = pathDir + "/dstDir/test.txt"; 713 fs.copyFile(srcPath, dstPath, 0, (err: BusinessError) => { 714 if (err) { 715 console.error("copy file failed with error message: " + err.message + ", error code: " + err.code); 716 } else { 717 console.info("copy file succeed"); 718 } 719 }); 720 ``` 721 722## fs.copyFile 723 724copyFile(src: string | number, dest: string | number, callback: AsyncCallback<void>): void 725 726复制文件,覆盖方式为完全覆盖目标文件,未覆盖部分将被裁切。使用callback异步回调。 727 728**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 729 730**系统能力**:SystemCapability.FileManagement.File.FileIO 731 732**参数:** 733 734 | 参数名 | 类型 | 必填 | 说明 | 735 | -------- | -------------------------- | ---- | ---------------------------------------- | 736 | src | string \| number | 是 | 待复制文件的路径或待复制文件的文件描述符。 | 737 | dest | string \| number | 是 | 目标文件路径或目标文件的文件描述符。 | 738 | callback | AsyncCallback<void> | 是 | 异步复制文件之后的回调。 | 739 740**错误码:** 741 742接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 743 744**示例:** 745 746 ```ts 747 import { BusinessError } from '@kit.BasicServicesKit'; 748 let srcPath = pathDir + "/srcDir/test.txt"; 749 let dstPath = pathDir + "/dstDir/test.txt"; 750 fs.copyFile(srcPath, dstPath, (err: BusinessError) => { 751 if (err) { 752 console.error("copy file failed with error message: " + err.message + ", error code: " + err.code); 753 } else { 754 console.info("copy file succeed"); 755 } 756 }); 757 ``` 758 759 760## fs.copyFileSync 761 762copyFileSync(src: string | number, dest: string | number, mode?: number): void 763 764以同步方法复制文件。 765 766**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 767 768**系统能力**:SystemCapability.FileManagement.File.FileIO 769 770**参数:** 771 772 | 参数名 | 类型 | 必填 | 说明 | 773 | ---- | -------------------------- | ---- | ---------------------------------------- | 774 | src | string \| number | 是 | 待复制文件的路径或待复制文件的文件描述符。 | 775 | dest | string \| number | 是 | 目标文件路径或目标文件的文件描述符。 | 776 | mode | number | 否 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。<br/>0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | 777 778**错误码:** 779 780接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 781 782**示例:** 783 784 ```ts 785 let srcPath = pathDir + "/srcDir/test.txt"; 786 let dstPath = pathDir + "/dstDir/test.txt"; 787 fs.copyFileSync(srcPath, dstPath); 788 ``` 789 790## fs.copyDir<sup>10+</sup> 791 792copyDir(src: string, dest: string, mode?: number): Promise\<void> 793 794复制源文件夹至目标路径下,使用Promise异步返回。 795 796**系统能力**:SystemCapability.FileManagement.File.FileIO 797 798**参数:** 799 800 | 参数名 | 类型 | 必填 | 说明 | 801 | ------ | ------ | ---- | --------------------------- | 802 | src | string | 是 | 源文件夹的应用沙箱路径。 | 803 | dest | string | 是 | 目标文件夹的应用沙箱路径。 | 804 | mode | number | 否 | 复制模式。默认mode为0。<br/>- mode为0,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为1,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。| 805 806**返回值:** 807 808 | 类型 | 说明 | 809 | ------------------- | ---------------------------- | 810 | Promise<void> | Promise对象。无返回值。 | 811 812**错误码:** 813 814接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 815 816**示例:** 817 818 ```ts 819 import { BusinessError } from '@kit.BasicServicesKit'; 820 // copy directory from srcPath to destPath 821 let srcPath = pathDir + "/srcDir/"; 822 let destPath = pathDir + "/destDir/"; 823 fs.copyDir(srcPath, destPath, 0).then(() => { 824 console.info("copy directory succeed"); 825 }).catch((err: BusinessError) => { 826 console.error("copy directory failed with error message: " + err.message + ", error code: " + err.code); 827 }); 828 ``` 829 830## fs.copyDir<sup>10+</sup> 831 832copyDir(src: string, dest: string, mode: number, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 833 834复制源文件夹至目标路径下,可设置复制模式。使用callback异步回调。 835 836**系统能力**:SystemCapability.FileManagement.File.FileIO 837 838**参数:** 839 840 | 参数名 | 类型 | 必填 | 说明 | 841 | ------ | ------ | ---- | --------------------------- | 842 | src | string | 是 | 源文件夹的应用沙箱路径。 | 843 | dest | string | 是 | 目标文件夹的应用沙箱路径。 | 844 | mode | number | 是 | 复制模式。默认mode为0。<br/>- mode为0,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为1,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。| 845 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | 是 | 异步复制文件夹之后的回调。 | 846 847**错误码:** 848 849接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 850 851**示例:** 852 853 ```ts 854 import { BusinessError } from '@kit.BasicServicesKit'; 855 import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 856 // copy directory from srcPath to destPath 857 let srcPath = pathDir + "/srcDir/"; 858 let destPath = pathDir + "/destDir/"; 859 fs.copyDir(srcPath, destPath, 0, (err: BusinessError<Array<ConflictFiles>>) => { 860 if (err && err.code == 13900015 && err.data?.length !== undefined) { 861 for (let i = 0; i < err.data.length; i++) { 862 console.error("copy directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 863 } 864 } else if (err) { 865 console.error("copy directory failed with error message: " + err.message + ", error code: " + err.code); 866 } else { 867 console.info("copy directory succeed"); 868 } 869 }); 870 ``` 871 872## fs.copyDir<sup>10+</sup> 873 874copyDir(src: string, dest: string, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 875 876复制源文件夹至目标路径下,使用Callback异步回调。 877 878当目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。 879 880**系统能力**:SystemCapability.FileManagement.File.FileIO 881 882**参数:** 883 884 | 参数名 | 类型 | 必填 | 说明 | 885 | ------ | ------ | ---- | --------------------------- | 886 | src | string | 是 | 源文件夹的应用沙箱路径。 | 887 | dest | string | 是 | 目标文件夹的应用沙箱路径。 | 888 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | 是 | 异步复制文件夹之后的回调。 | 889 890**错误码:** 891 892接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 893 894**示例:** 895 896 ```ts 897 import { BusinessError } from '@kit.BasicServicesKit'; 898 import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 899 // copy directory from srcPath to destPath 900 let srcPath = pathDir + "/srcDir/"; 901 let destPath = pathDir + "/destDir/"; 902 fs.copyDir(srcPath, destPath, (err: BusinessError<Array<ConflictFiles>>) => { 903 if (err && err.code == 13900015 && err.data?.length !== undefined) { 904 for (let i = 0; i < err.data.length; i++) { 905 console.error("copy directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 906 } 907 } else if (err) { 908 console.error("copy directory failed with error message: " + err.message + ", error code: " + err.code); 909 } else { 910 console.info("copy directory succeed"); 911 } 912 }); 913 ``` 914 915## fs.copyDirSync<sup>10+</sup> 916 917copyDirSync(src: string, dest: string, mode?: number): void 918 919以同步方法复制源文件夹至目标路径下。 920 921**系统能力**:SystemCapability.FileManagement.File.FileIO 922 923**参数:** 924 925 | 参数名 | 类型 | 必填 | 说明 | 926 | ------ | ------ | ---- | --------------------------- | 927 | src | string | 是 | 源文件夹的应用沙箱路径。 | 928 | dest | string | 是 | 目标文件夹的应用沙箱路径。 | 929 | mode | number | 否 | 复制模式。默认mode为0。<br/>- mode为0,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为1,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。| 930 931**错误码:** 932 933接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 934 935**示例:** 936 937 ```ts 938 import { BusinessError } from '@kit.BasicServicesKit'; 939 // copy directory from srcPath to destPath 940 let srcPath = pathDir + "/srcDir/"; 941 let destPath = pathDir + "/destDir/"; 942 try { 943 fs.copyDirSync(srcPath, destPath, 0); 944 console.info("copy directory succeed"); 945 } catch (error) { 946 let err: BusinessError = error as BusinessError; 947 console.error("copy directory failed with error message: " + err.message + ", error code: " + err.code); 948 } 949 ``` 950 951## fs.dup<sup>10+</sup> 952 953dup(fd: number): File 954 955将文件描述符转化为File。 956 957**系统能力**:SystemCapability.FileManagement.File.FileIO 958 959**参数:** 960 961 | 参数名 | 类型 | 必填 | 说明 | 962 | ------ | ------ | ---- | --------------------------- | 963 | fd | number | 是 | 文件描述符。 | 964 965**返回值:** 966 967 | 类型 | 说明 | 968 | ------------------- | ---------------------------- | 969 | [File](#file) | 打开的File对象。 | 970 971**错误码:** 972 973接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 974 975**示例:** 976 977 ```ts 978 let filePath = pathDir + "/test.txt"; 979 let file1 = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 980 let fd: number = file1.fd; 981 let file2 = fs.dup(fd); 982 console.info("The name of the file2 is " + file2.name); 983 fs.closeSync(file1); 984 fs.closeSync(file2); 985 ``` 986 987## fs.connectDfs<sup>12+</sup> 988 989connectDfs(networkId: string, listeners: DfsListeners): Promise<void> 990 991业务调用connectDfs接口,触发建链。如果对端设备出现异常,业务执行回调DfsListeners内[onStatus](#onstatus12)通知应用。 992 993**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC 994 995**系统能力**:SystemCapability.FileManagement.File.FileIO 996 997**参数:** 998 999 | 参数名 | 类型 | 必填 | 说明 | 1000 | ---- | ------ | ---- | ---------------------------------------- | 1001 | networkId | string | 是 | 设备的网络Id。通过[distributedDeviceManager](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md)接口调用[deviceBasicInfo](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#devicebasicinfo)获得。 | 1002 | listeners | [DfsListeners](#fsdfslisteners12) | 是 | 分布式文件系统状态监听器。 | 1003 1004**返回值:** 1005 1006 | 类型 | 说明 | 1007 | ------ | ---------------------------------------- | 1008 | Promise<void>| Promise对象。无返回值。 | 1009 1010**错误码:** 1011 1012接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1013 1014**示例:** 1015 1016 ```ts 1017 import { BusinessError } from '@kit.BasicServicesKit'; 1018 import { fileIo as fs } from '@kit.CoreFileKit'; 1019 import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 1020 let dmInstance = distributedDeviceManager.createDeviceManager("com.example.filesync"); 1021 let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync(); 1022 let networkId = deviceInfoList[0].networkId; 1023 let listeners: fs.DfsListeners = { 1024 onStatus(networkId, status) { 1025 console.info('onStatus'); 1026 } 1027 } 1028 fs.connectDfs(networkId, listeners).then(() => { 1029 console.info("Success to connectDfs"); 1030 }).catch((err: BusinessError) => { 1031 console.error("connectDfs failed with error message: " + err.message + ", error code: " + err.code); 1032 }); 1033 ``` 1034 1035## fs.disconnectDfs<sup>12+</sup> 1036 1037disconnectDfs(networkId: string): Promise<void> 1038 1039业务调用disconnectDfs接口,传入networkId参数,触发断链。 1040 1041**需要权限**:ohos.permission.DISTRIBUTED_DATASYNC 1042 1043**系统能力**:SystemCapability.FileManagement.File.FileIO 1044 1045**参数:** 1046 1047 | 参数名 | 类型 | 必填 | 说明 | 1048 | ---- | ------ | ---- | ---------------------------------------- | 1049 | networkId | string | 是 | 设备的网络Id。通过[distributedDeviceManager](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md)接口调用[deviceBasicInfo](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#devicebasicinfo)获得。 | 1050 1051**返回值:** 1052 1053 | 类型 | 说明 | 1054 | ------ | ---------------------------------------- | 1055 | Promise<void>| Promise对象。无返回值。 | 1056 1057**错误码:** 1058 1059接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1060 1061**示例:** 1062 1063 ```ts 1064 import { BusinessError } from '@kit.BasicServicesKit'; 1065 import { fileIo as fs } from '@kit.CoreFileKit'; 1066 import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 1067 let dmInstance = distributedDeviceManager.createDeviceManager("com.example.filesync"); 1068 let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync(); 1069 let networkId = deviceInfoList[0].networkId; 1070 fs.disconnectDfs(networkId).then(() => { 1071 console.info("Success to disconnectDfs"); 1072 }).catch((err: BusinessError) => { 1073 console.error('disconnectDfs failed with error message: ${JSON.stringify(err)}') 1074 }) 1075 ``` 1076 1077## fs.setxattr<sup>12+</sup> 1078 1079setxattr(path: string, key: string, value: string): Promise<void> 1080 1081设置文件的扩展属性。 1082 1083**系统能力**:SystemCapability.FileManagement.File.FileIO 1084 1085**参数:** 1086 1087| 参数名 | 类型 | 必填 | 说明 | 1088| ------ | ------ | ---- | ------------------------------------------------------------ | 1089| path | string | 是 | 目录的应用沙箱路径。 | 1090| key | string | 是 | 扩展属性的key,仅支持前缀为“user.”的字符串,且长度需小于256字节。 | 1091| value | string | 是 | 扩展属性的value。 | 1092 1093**返回值:** 1094 1095 | 类型 | 说明 | 1096 | ------ | ---------------------------------------- | 1097 | Promise<void>| Promise对象。无返回值。 | 1098 1099**错误码:** 1100 1101接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1102 1103**示例:** 1104 1105 ```ts 1106 import { BusinessError } from '@kit.BasicServicesKit'; 1107 1108 let filePath = pathDir + "/test.txt"; 1109 let attrKey = "user.comment"; 1110 let attrValue = "Test file."; 1111 1112 fs.setxattr(filePath, attrKey, attrValue).then(() => { 1113 console.info("Set extended attribute successfully."); 1114 }).catch((err: BusinessError) => { 1115 console.error("Failed to set extended attribute with error message: " + err.message + ", error code: " + err.code); 1116 }); 1117 1118 ``` 1119## fs.setxattrSync<sup>12+</sup> 1120 1121setxattrSync(path: string, key: string, value: string): void 1122 1123设置文件的扩展属性。 1124 1125**系统能力**:SystemCapability.FileManagement.File.FileIO 1126 1127**参数:** 1128 1129| 参数名 | 类型 | 必填 | 说明 | 1130| ------ | ------ | ---- | ------------------------------------------------------------ | 1131| path | string | 是 | 目录的应用沙箱路径。 | 1132| key | string | 是 | 扩展属性的key,仅支持前缀为“user.”的字符串,且长度需小于256字节。 | 1133| value | string | 是 | 扩展属性的value。 | 1134 1135**错误码:** 1136 1137接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1138 1139**示例:** 1140 1141 ```ts 1142 import { BusinessError } from '@kit.BasicServicesKit'; 1143 1144 let filePath = pathDir + "/test.txt"; 1145 let attrKey = "user.comment"; 1146 let attrValue = "Test file."; 1147 1148 try { 1149 fs.setxattrSync(filePath, attrKey, attrValue); 1150 console.info("Set extended attribute successfully."); 1151 } catch (err) { 1152 console.error("Failed to set extended attribute with error message: " + err.message + ", error code: " + err.code); 1153 } 1154 1155 ``` 1156 1157## fs.getxattr<sup>12+</sup> 1158 1159getxattr(path: string, key: string): Promise<string> 1160 1161获取文件的扩展属性。 1162 1163**系统能力**:SystemCapability.FileManagement.File.FileIO 1164 1165**参数:** 1166 1167| 参数名 | 类型 | 必填 | 说明 | 1168| ------ | ------ | ---- | ------------------------------------------------------------ | 1169| path | string | 是 | 目录的应用沙箱路径。 | 1170| key | string | 是 | 扩展属性的key。 | 1171 1172**返回值:** 1173 1174 | 类型 | 说明 | 1175 | ------ | ---------------------------------------- | 1176 | Promise<string>| Promise对象。返回扩展属性的value。 | 1177 1178**错误码:** 1179 1180接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1181 1182**示例:** 1183 1184 ```ts 1185 import { BusinessError } from '@kit.BasicServicesKit'; 1186 1187 let filePath = pathDir + "/test.txt"; 1188 let attrKey = "user.comment"; 1189 1190 fs.getxattr(filePath, attrKey).then((attrValue: string) => { 1191 console.info("Get extended attribute succeed, the value is: " + attrValue); 1192 }).catch((err: BusinessError) => { 1193 console.error("Failed to get extended attribute with error message: " + err.message + ", error code: " + err.code); 1194 }); 1195 1196 ``` 1197 1198## fs.getxattrSync<sup>12+</sup> 1199 1200getxattrSync(path: string, key: string): string 1201 1202使用同步接口获取文件的扩展属性。 1203 1204**系统能力**:SystemCapability.FileManagement.File.FileIO 1205 1206**参数:** 1207 1208| 参数名 | 类型 | 必填 | 说明 | 1209| ------ | ------ | ---- | ------------------------------------------------------------ | 1210| path | string | 是 | 目录的应用沙箱路径。 | 1211| key | string | 是 | 扩展属性的key。 | 1212 1213**返回值:** 1214 1215 | 类型 | 说明 | 1216 | ------ | ---------------------------------------- | 1217 | key| string对象。返回扩展属性的value。 | 1218 1219**错误码:** 1220 1221接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1222 1223**示例:** 1224 1225 ```ts 1226 import { BusinessError } from '@kit.BasicServicesKit'; 1227 1228 let filePath = pathDir + "/test.txt"; 1229 let attrKey = "user.comment"; 1230 1231 try { 1232 let attrValue = fs.getxattrSync(filePath, attrKey); 1233 console.info("Get extended attribute succeed, the value is: " + attrValue); 1234 } catch (err) { 1235 console.error("Failed to get extended attribute with error message: " + err.message + ", error code: " + err.code); 1236 } 1237 1238 ``` 1239 1240## fs.mkdir 1241 1242mkdir(path: string): Promise<void> 1243 1244创建目录,使用Promise异步返回。 1245 1246**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1247 1248**系统能力**:SystemCapability.FileManagement.File.FileIO 1249 1250**参数:** 1251 1252| 参数名 | 类型 | 必填 | 说明 | 1253| ------ | ------ | ---- | ------------------------------------------------------------ | 1254| path | string | 是 | 目录的应用沙箱路径。 | 1255 1256**返回值:** 1257 1258 | 类型 | 说明 | 1259 | ------------------- | ---------------------------- | 1260 | Promise<void> | Promise对象。无返回值。 | 1261 1262**错误码:** 1263 1264接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1265 1266**示例:** 1267 1268 ```ts 1269 import { BusinessError } from '@kit.BasicServicesKit'; 1270 let dirPath = pathDir + "/testDir"; 1271 fs.mkdir(dirPath).then(() => { 1272 console.info("mkdir succeed"); 1273 }).catch((err: BusinessError) => { 1274 console.error("mkdir failed with error message: " + err.message + ", error code: " + err.code); 1275 }); 1276 ``` 1277 1278## fs.mkdir<sup>11+</sup> 1279 1280mkdir(path: string, recursion: boolean): Promise\<void> 1281 1282创建目录,使用Promise异步返回。当recursion指定为true,可多层级创建目录。 1283 1284**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1285 1286**系统能力**:SystemCapability.FileManagement.File.FileIO 1287 1288**参数:** 1289 1290| 参数名 | 类型 | 必填 | 说明 | 1291| ------ | ------ | ---- | ------------------------------------------------------------ | 1292| path | string | 是 | 目录的应用沙箱路径。 | 1293| recursion | boolean | 是 | 是否多层级创建目录。recursion指定为true时,可多层级创建目录。recursion指定为false时,仅可创建单层目录。 | 1294 1295**返回值:** 1296 1297 | 类型 | 说明 | 1298 | ------------------- | ---------------------------- | 1299 | Promise<void> | Promise对象。无返回值。 | 1300 1301**错误码:** 1302 1303接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1304 1305**示例:** 1306 1307 ```ts 1308 import { BusinessError } from '@kit.BasicServicesKit'; 1309 let dirPath = pathDir + "/testDir1/testDir2/testDir3"; 1310 fs.mkdir(dirPath, true).then(() => { 1311 console.info("mkdir succeed"); 1312 }).catch((err: BusinessError) => { 1313 console.error("mkdir failed with error message: " + err.message + ", error code: " + err.code); 1314 }); 1315 ``` 1316 1317## fs.mkdir 1318 1319mkdir(path: string, callback: AsyncCallback<void>): void 1320 1321创建目录,使用callback异步回调。 1322 1323**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1324 1325**系统能力**:SystemCapability.FileManagement.File.FileIO 1326 1327**参数:** 1328 1329| 参数名 | 类型 | 必填 | 说明 | 1330| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 1331| path | string | 是 | 目录的应用沙箱路径。 | 1332| callback | AsyncCallback<void> | 是 | 异步创建目录操作完成之后的回调。 | 1333 1334**错误码:** 1335 1336接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1337 1338**示例:** 1339 1340 ```ts 1341 import { BusinessError } from '@kit.BasicServicesKit'; 1342 let dirPath = pathDir + "/testDir"; 1343 fs.mkdir(dirPath, (err: BusinessError) => { 1344 if (err) { 1345 console.error("mkdir failed with error message: " + err.message + ", error code: " + err.code); 1346 } else { 1347 console.info("mkdir succeed"); 1348 } 1349 }); 1350 ``` 1351 1352## fs.mkdir<sup>11+</sup> 1353 1354mkdir(path: string, recursion: boolean, callback: AsyncCallback<void>): void 1355 1356创建目录,使用callback异步回调。当recursion指定为true,可多层级创建目录。 1357 1358**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1359 1360**系统能力**:SystemCapability.FileManagement.File.FileIO 1361 1362**参数:** 1363 1364| 参数名 | 类型 | 必填 | 说明 | 1365| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 1366| path | string | 是 | 目录的应用沙箱路径。 | 1367| recursion | boolean | 是 | 是否多层级创建目录。recursion指定为true时,可多层级创建目录。recursion指定为false时,仅可创建单层目录。 | 1368| callback | AsyncCallback<void> | 是 | 异步创建目录操作完成之后的回调。 | 1369 1370**错误码:** 1371 1372接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1373 1374**示例:** 1375 1376 ```ts 1377 import { BusinessError } from '@kit.BasicServicesKit'; 1378 let dirPath = pathDir + "/testDir1/testDir2/testDir3"; 1379 fs.mkdir(dirPath, true, (err: BusinessError) => { 1380 if (err) { 1381 console.error("mkdir failed with error message: " + err.message + ", error code: " + err.code); 1382 } else { 1383 console.info("mkdir succeed"); 1384 } 1385 }); 1386 ``` 1387 1388## fs.mkdirSync 1389 1390mkdirSync(path: string): void 1391 1392以同步方法创建目录。 1393 1394**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1395 1396**系统能力**:SystemCapability.FileManagement.File.FileIO 1397 1398**参数:** 1399 1400| 参数名 | 类型 | 必填 | 说明 | 1401| ------ | ------ | ---- | ------------------------------------------------------------ | 1402| path | string | 是 | 目录的应用沙箱路径。 | 1403 1404**错误码:** 1405 1406接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1407 1408**示例:** 1409 1410 ```ts 1411 let dirPath = pathDir + "/testDir"; 1412 fs.mkdirSync(dirPath); 1413 ``` 1414 1415## fs.mkdirSync<sup>11+</sup> 1416 1417mkdirSync(path: string, recursion: boolean): void 1418 1419以同步方法创建目录。当recursion指定为true,可多层级创建目录。 1420 1421**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1422 1423**系统能力**:SystemCapability.FileManagement.File.FileIO 1424 1425**参数:** 1426 1427| 参数名 | 类型 | 必填 | 说明 | 1428| ------ | ------ | ---- | ------------------------------------------------------------ | 1429| path | string | 是 | 目录的应用沙箱路径。 | 1430| recursion | boolean | 是 | 是否多层级创建目录。recursion指定为true时,可多层级创建目录。recursion指定为false时,仅可创建单层目录。 | 1431 1432**错误码:** 1433 1434接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1435 1436**示例:** 1437 1438 ```ts 1439 let dirPath = pathDir + "/testDir1/testDir2/testDir3"; 1440 fs.mkdirSync(dirPath, true); 1441 ``` 1442 1443## fs.open 1444 1445open(path: string, mode?: number): Promise<File> 1446 1447打开文件,使用Promise异步返回。支持使用URI打开文件。 1448 1449**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1450 1451**系统能力**:SystemCapability.FileManagement.File.FileIO 1452 1453**参数:** 1454 1455| 参数名 | 类型 | 必填 | 说明 | 1456| ------ | ------ | ---- | ------------------------------------------------------------ | 1457| path | string | 是 | 文件的应用沙箱路径或文件URI。 | 1458| mode | number | 否 | 打开文件的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:<br/>- OpenMode.READ_ONLY(0o0):只读打开。<br/>- OpenMode.WRITE_ONLY(0o1):只写打开。<br/>- OpenMode.READ_WRITE(0o2):读写打开。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果文件存在且文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | 1459 1460**返回值:** 1461 1462 | 类型 | 说明 | 1463 | --------------------- | ----------- | 1464 | Promise<[File](#file)> | Promise对象。返回File对象。 | 1465 1466**错误码:** 1467 1468接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1469 1470**示例:** 1471 1472 ```ts 1473 import { BusinessError } from '@kit.BasicServicesKit'; 1474 let filePath = pathDir + "/test.txt"; 1475 fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file: fs.File) => { 1476 console.info("file fd: " + file.fd); 1477 fs.closeSync(file); 1478 }).catch((err: BusinessError) => { 1479 console.error("open file failed with error message: " + err.message + ", error code: " + err.code); 1480 }); 1481 ``` 1482 1483 1484## fs.open 1485 1486open(path: string, mode: number, callback: AsyncCallback<File>): void 1487 1488打开文件,可设置打开文件的选项。使用callback异步回调。 1489 1490支持使用URI打开文件。 1491 1492**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1493 1494**系统能力**:SystemCapability.FileManagement.File.FileIO 1495 1496**参数:** 1497 1498| 参数名 | 类型 | 必填 | 说明 | 1499| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 1500| path | string | 是 | 文件的应用沙箱路径或URI。 | 1501| mode | number | 是 | 打开文件的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:<br/>- OpenMode.READ_ONLY(0o0):只读打开。<br/>- OpenMode.WRITE_ONLY(0o1):只写打开。<br/>- OpenMode.READ_WRITE(0o2):读写打开。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果文件存在且文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | 1502| callback | AsyncCallback<void> | 是 | 异步打开文件之后的回调。 | 1503 1504**错误码:** 1505 1506接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1507 1508**示例:** 1509 1510 ```ts 1511 import { BusinessError } from '@kit.BasicServicesKit'; 1512 let filePath = pathDir + "/test.txt"; 1513 fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE, (err: BusinessError, file: fs.File) => { 1514 if (err) { 1515 console.error("open failed with error message: " + err.message + ", error code: " + err.code); 1516 } else { 1517 console.info("file fd: " + file.fd); 1518 fs.closeSync(file); 1519 } 1520 }); 1521 ``` 1522 1523## fs.open 1524 1525open(path: string, callback: AsyncCallback<File>): void 1526 1527打开文件,使用callback异步回调。支持使用URI打开文件。 1528 1529**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1530 1531**系统能力**:SystemCapability.FileManagement.File.FileIO 1532 1533**参数:** 1534 1535| 参数名 | 类型 | 必填 | 说明 | 1536| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 1537| path | string | 是 | 文件的应用沙箱路径或URI。 | 1538| callback | AsyncCallback<void> | 是 | 异步打开文件之后的回调。 | 1539 1540**错误码:** 1541 1542接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1543 1544**示例:** 1545 1546 ```ts 1547 import { BusinessError } from '@kit.BasicServicesKit'; 1548 let filePath = pathDir + "/test.txt"; 1549 fs.open(filePath, (err: BusinessError, file: fs.File) => { 1550 if (err) { 1551 console.error("open failed with error message: " + err.message + ", error code: " + err.code); 1552 } else { 1553 console.info("file fd: " + file.fd); 1554 fs.closeSync(file); 1555 } 1556 }); 1557 ``` 1558 1559## fs.openSync 1560 1561openSync(path: string, mode?: number): File 1562 1563以同步方法打开文件。支持使用URI打开文件。 1564 1565**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1566 1567**系统能力**:SystemCapability.FileManagement.File.FileIO 1568 1569**参数:** 1570 1571| 参数名 | 类型 | 必填 | 说明 | 1572| ------ | ------ | ---- | ------------------------------------------------------------ | 1573| path | string | 是 | 打开文件的应用沙箱路径或URI。 | 1574| mode | number | 否 | 打开文件的[选项](#openmode),必须指定如下选项中的一个,默认以只读方式打开:<br/>- OpenMode.READ_ONLY(0o0):只读打开。<br/>- OpenMode.WRITE_ONLY(0o1):只写打开。<br/>- OpenMode.READ_WRITE(0o2):读写打开。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果文件存在且文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | 1575 1576**返回值:** 1577 1578 | 类型 | 说明 | 1579 | ------ | ----------- | 1580 | [File](#file) | 打开的File对象。 | 1581 1582**错误码:** 1583 1584接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1585 1586**示例:** 1587 1588 ```ts 1589 let filePath = pathDir + "/test.txt"; 1590 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1591 console.info("file fd: " + file.fd); 1592 fs.closeSync(file); 1593 ``` 1594 1595## fs.read 1596 1597read(fd: number, buffer: ArrayBuffer, options?: ReadOptions): Promise<number> 1598 1599从文件读取数据,使用Promise异步返回。 1600 1601**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1602 1603**系统能力**:SystemCapability.FileManagement.File.FileIO 1604 1605**参数:** 1606 1607| 参数名 | 类型 | 必填 | 说明 | 1608| ------- | ----------- | ---- | ------------------------------------------------------------ | 1609| fd | number | 是 | 已打开的文件描述符。 | 1610| buffer | ArrayBuffer | 是 | 用于保存读取到的文件数据的缓冲区。 | 1611| options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。| 1612 1613**返回值:** 1614 1615 | 类型 | 说明 | 1616 | ---------------------------------- | ------ | 1617 | Promise<number> | Promise对象。返回实际读取的数据长度,单位字节。| 1618 1619**错误码:** 1620 1621接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1622 1623**示例:** 1624 1625 ```ts 1626 import { BusinessError } from '@kit.BasicServicesKit'; 1627 import { buffer } from '@kit.ArkTS'; 1628 let filePath = pathDir + "/test.txt"; 1629 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 1630 let arrayBuffer = new ArrayBuffer(4096); 1631 fs.read(file.fd, arrayBuffer).then((readLen: number) => { 1632 console.info("read file data succeed"); 1633 let buf = buffer.from(arrayBuffer, 0, readLen); 1634 console.info(`The content of file: ${buf.toString()}`); 1635 }).catch((err: BusinessError) => { 1636 console.error("read file data failed with error message: " + err.message + ", error code: " + err.code); 1637 }).finally(() => { 1638 fs.closeSync(file); 1639 }); 1640 ``` 1641 1642## fs.read 1643 1644read(fd: number, buffer: ArrayBuffer, options?: ReadOptions, callback: AsyncCallback<number>): void 1645 1646从文件读取数据,使用callback异步回调。 1647 1648**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1649 1650**系统能力**:SystemCapability.FileManagement.File.FileIO 1651 1652**参数:** 1653 1654 | 参数名 | 类型 | 必填 | 说明 | 1655 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1656 | fd | number | 是 | 已打开的文件描述符。 | 1657 | buffer | ArrayBuffer | 是 | 用于保存读取到的文件数据的缓冲区。 | 1658 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。| 1659 | callback | AsyncCallback<number> | 是 | 异步读取数据之后的回调。返回实际读取的数据长度,单位字节。 | 1660 1661**错误码:** 1662 1663接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1664 1665**示例:** 1666 1667 ```ts 1668 import { BusinessError } from '@kit.BasicServicesKit'; 1669 import { buffer } from '@kit.ArkTS'; 1670 let filePath = pathDir + "/test.txt"; 1671 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 1672 let arrayBuffer = new ArrayBuffer(4096); 1673 fs.read(file.fd, arrayBuffer, (err: BusinessError, readLen: number) => { 1674 if (err) { 1675 console.error("read failed with error message: " + err.message + ", error code: " + err.code); 1676 } else { 1677 console.info("read file data succeed"); 1678 let buf = buffer.from(arrayBuffer, 0, readLen); 1679 console.info(`The content of file: ${buf.toString()}`); 1680 } 1681 fs.closeSync(file); 1682 }); 1683 ``` 1684 1685## fs.readSync 1686 1687readSync(fd: number, buffer: ArrayBuffer, options?: ReadOptions): number 1688 1689以同步方法从文件读取数据。 1690 1691**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1692 1693**系统能力**:SystemCapability.FileManagement.File.FileIO 1694 1695**参数:** 1696 1697 | 参数名 | 类型 | 必填 | 说明 | 1698 | ------- | ----------- | ---- | ---------------------------------------- | 1699 | fd | number | 是 | 已打开的文件描述符。 | 1700 | buffer | ArrayBuffer | 是 | 用于保存读取到的文件数据的缓冲区。 | 1701 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。| 1702 1703**返回值:** 1704 1705 | 类型 | 说明 | 1706 | ------ | -------- | 1707 | number | 返回实际读取的数据长度,单位字节。 | 1708 1709**错误码:** 1710 1711接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1712 1713**示例:** 1714 1715 ```ts 1716 let filePath = pathDir + "/test.txt"; 1717 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 1718 let buf = new ArrayBuffer(4096); 1719 fs.readSync(file.fd, buf); 1720 fs.closeSync(file); 1721 ``` 1722 1723## fs.rmdir 1724 1725rmdir(path: string): Promise<void> 1726 1727删除整个目录,使用Promise异步返回。 1728 1729**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1730 1731**系统能力**:SystemCapability.FileManagement.File.FileIO 1732 1733**参数:** 1734 1735| 参数名 | 类型 | 必填 | 说明 | 1736| ------ | ------ | ---- | -------------------------- | 1737| path | string | 是 | 目录的应用沙箱路径。 | 1738 1739**返回值:** 1740 1741 | 类型 | 说明 | 1742 | ------------------- | ---------------------------- | 1743 | Promise<void> | Promise对象。无返回值。 | 1744 1745**错误码:** 1746 1747接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1748 1749**示例:** 1750 1751 ```ts 1752 import { BusinessError } from '@kit.BasicServicesKit'; 1753 let dirPath = pathDir + "/testDir"; 1754 fs.rmdir(dirPath).then(() => { 1755 console.info("rmdir succeed"); 1756 }).catch((err: BusinessError) => { 1757 console.error("rmdir failed with error message: " + err.message + ", error code: " + err.code); 1758 }); 1759 ``` 1760 1761## fs.rmdir 1762 1763rmdir(path: string, callback: AsyncCallback<void>): void 1764 1765删除整个目录,使用callback异步回调。 1766 1767**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1768 1769**系统能力**:SystemCapability.FileManagement.File.FileIO 1770 1771**参数:** 1772 1773| 参数名 | 类型 | 必填 | 说明 | 1774| -------- | ------------------------- | ---- | -------------------------- | 1775| path | string | 是 | 目录的应用沙箱路径。 | 1776| callback | AsyncCallback<void> | 是 | 异步删除目录之后的回调。 | 1777 1778**错误码:** 1779 1780接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1781 1782**示例:** 1783 1784 ```ts 1785 import { BusinessError } from '@kit.BasicServicesKit'; 1786 let dirPath = pathDir + "/testDir"; 1787 fs.rmdir(dirPath, (err: BusinessError) => { 1788 if (err) { 1789 console.error("rmdir failed with error message: " + err.message + ", error code: " + err.code); 1790 } else { 1791 console.info("rmdir succeed"); 1792 } 1793 }); 1794 ``` 1795 1796## fs.rmdirSync 1797 1798rmdirSync(path: string): void 1799 1800以同步方法删除目录。 1801 1802**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1803 1804**系统能力**:SystemCapability.FileManagement.File.FileIO 1805 1806**参数:** 1807 1808| 参数名 | 类型 | 必填 | 说明 | 1809| ------ | ------ | ---- | -------------------------- | 1810| path | string | 是 | 目录的应用沙箱路径。 | 1811 1812**错误码:** 1813 1814接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1815 1816**示例:** 1817 1818 ```ts 1819 let dirPath = pathDir + "/testDir"; 1820 fs.rmdirSync(dirPath); 1821 ``` 1822 1823## fs.unlink 1824 1825unlink(path: string): Promise<void> 1826 1827删除单个文件,使用Promise异步返回。 1828 1829**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1830 1831**系统能力**:SystemCapability.FileManagement.File.FileIO 1832 1833**参数:** 1834 1835| 参数名 | 类型 | 必填 | 说明 | 1836| ------ | ------ | ---- | -------------------------- | 1837| path | string | 是 | 文件的应用沙箱路径。 | 1838 1839**返回值:** 1840 1841 | 类型 | 说明 | 1842 | ------------------- | ---------------------------- | 1843 | Promise<void> | Promise对象。无返回值。 | 1844 1845**错误码:** 1846 1847接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1848 1849**示例:** 1850 1851 ```ts 1852 import { BusinessError } from '@kit.BasicServicesKit'; 1853 let filePath = pathDir + "/test.txt"; 1854 fs.unlink(filePath).then(() => { 1855 console.info("remove file succeed"); 1856 }).catch((err: BusinessError) => { 1857 console.error("remove file failed with error message: " + err.message + ", error code: " + err.code); 1858 }); 1859 ``` 1860 1861## fs.unlink 1862 1863unlink(path: string, callback: AsyncCallback<void>): void 1864 1865删除文件,使用callback异步回调。 1866 1867**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1868 1869**系统能力**:SystemCapability.FileManagement.File.FileIO 1870 1871**参数:** 1872 1873| 参数名 | 类型 | 必填 | 说明 | 1874| -------- | ------------------------- | ---- | -------------------------- | 1875| path | string | 是 | 文件的应用沙箱路径。 | 1876| callback | AsyncCallback<void> | 是 | 异步删除文件之后的回调。 | 1877 1878**错误码:** 1879 1880接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1881 1882**示例:** 1883 1884 ```ts 1885 import { BusinessError } from '@kit.BasicServicesKit'; 1886 let filePath = pathDir + "/test.txt"; 1887 fs.unlink(filePath, (err: BusinessError) => { 1888 if (err) { 1889 console.error("remove file failed with error message: " + err.message + ", error code: " + err.code); 1890 } else { 1891 console.info("remove file succeed"); 1892 } 1893 }); 1894 ``` 1895 1896## fs.unlinkSync 1897 1898unlinkSync(path: string): void 1899 1900以同步方法删除文件。 1901 1902**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1903 1904**系统能力**:SystemCapability.FileManagement.File.FileIO 1905 1906**参数:** 1907 1908| 参数名 | 类型 | 必填 | 说明 | 1909| ------ | ------ | ---- | -------------------------- | 1910| path | string | 是 | 文件的应用沙箱路径。 | 1911 1912**错误码:** 1913 1914接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1915 1916**示例:** 1917 1918 ```ts 1919 let filePath = pathDir + "/test.txt"; 1920 fs.unlinkSync(filePath); 1921 ``` 1922 1923 1924## fs.write 1925 1926write(fd: number, buffer: ArrayBuffer | string, options?: WriteOptions): Promise<number> 1927 1928将数据写入文件,使用Promise异步返回。 1929 1930**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1931 1932**系统能力**:SystemCapability.FileManagement.File.FileIO 1933 1934**参数:** 1935 1936 | 参数名 | 类型 | 必填 | 说明 | 1937 | ------- | ------------------------------- | ---- | ---------------------------------------- | 1938 | fd | number | 是 | 已打开的文件描述符。 | 1939 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 1940 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。当前仅支持 'utf-8'。| 1941 1942**返回值:** 1943 1944 | 类型 | 说明 | 1945 | --------------------- | -------- | 1946 | Promise<number> | Promise对象。返回实际写入的数据长度,单位字节。 | 1947 1948**错误码:** 1949 1950接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1951 1952**示例:** 1953 1954 ```ts 1955 import { BusinessError } from '@kit.BasicServicesKit'; 1956 let filePath = pathDir + "/test.txt"; 1957 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1958 let str: string = "hello, world"; 1959 fs.write(file.fd, str).then((writeLen: number) => { 1960 console.info("write data to file succeed and size is:" + writeLen); 1961 }).catch((err: BusinessError) => { 1962 console.error("write data to file failed with error message: " + err.message + ", error code: " + err.code); 1963 }).finally(() => { 1964 fs.closeSync(file); 1965 }); 1966 ``` 1967 1968## fs.write 1969 1970write(fd: number, buffer: ArrayBuffer | string, options?: WriteOptions, callback: AsyncCallback<number>): void 1971 1972将数据写入文件,使用callback异步回调。 1973 1974**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 1975 1976**系统能力**:SystemCapability.FileManagement.File.FileIO 1977 1978**参数:** 1979 1980 | 参数名 | 类型 | 必填 | 说明 | 1981 | -------- | ------------------------------- | ---- | ---------------------------------------- | 1982 | fd | number | 是 | 已打开的文件描述符。 | 1983 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 1984 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。当前仅支持 'utf-8'。| 1985 | callback | AsyncCallback<number> | 是 | 异步将数据写入完成后执行的回调函数。 | 1986 1987**错误码:** 1988 1989接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 1990 1991**示例:** 1992 1993 ```ts 1994 import { BusinessError } from '@kit.BasicServicesKit'; 1995 let filePath = pathDir + "/test.txt"; 1996 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1997 let str: string = "hello, world"; 1998 fs.write(file.fd, str, (err: BusinessError, writeLen: number) => { 1999 if (err) { 2000 console.error("write data to file failed with error message:" + err.message + ", error code: " + err.code); 2001 } else { 2002 console.info("write data to file succeed and size is:" + writeLen); 2003 } 2004 fs.closeSync(file); 2005 }); 2006 ``` 2007 2008## fs.writeSync 2009 2010writeSync(fd: number, buffer: ArrayBuffer | string, options?: WriteOptions): number 2011 2012以同步方法将数据写入文件。 2013 2014**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2015 2016**系统能力**:SystemCapability.FileManagement.File.FileIO 2017 2018**参数:** 2019 2020 | 参数名 | 类型 | 必填 | 说明 | 2021 | ------- | ------------------------------- | ---- | ---------------------------------------- | 2022 | fd | number | 是 | 已打开的文件描述符。 | 2023 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 2024 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。当前仅支持 'utf-8'。| 2025 2026**返回值:** 2027 2028 | 类型 | 说明 | 2029 | ------ | -------- | 2030 | number | 返回实际写入的数据长度,单位字节。 | 2031 2032**错误码:** 2033 2034接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2035 2036**示例:** 2037 2038 ```ts 2039 let filePath = pathDir + "/test.txt"; 2040 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 2041 let str: string = "hello, world"; 2042 let writeLen = fs.writeSync(file.fd, str); 2043 console.info("write data to file succeed and size is:" + writeLen); 2044 fs.closeSync(file); 2045 ``` 2046 2047## fs.truncate 2048 2049truncate(file: string | number, len?: number): Promise<void> 2050 2051截断文件内容,使用Promise异步返回。 2052 2053**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2054 2055**系统能力**:SystemCapability.FileManagement.File.FileIO 2056 2057**参数:** 2058 2059| 参数名 | 类型 | 必填 | 说明 | 2060| ------ | ------ | ---- | -------------------------------- | 2061| file | string \| number | 是 | 文件的应用沙箱路径或已打开的文件描述符fd。 | 2062| len | number | 否 | 文件截断后的长度,以字节为单位。默认为0。 | 2063 2064**返回值:** 2065 2066 | 类型 | 说明 | 2067 | ------------------- | ---------------------------- | 2068 | Promise<void> | Promise对象。无返回值。 | 2069 2070**错误码:** 2071 2072接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2073 2074**示例:** 2075 2076 ```ts 2077 import { BusinessError } from '@kit.BasicServicesKit'; 2078 let filePath = pathDir + "/test.txt"; 2079 let len: number = 5; 2080 fs.truncate(filePath, len).then(() => { 2081 console.info("truncate file succeed"); 2082 }).catch((err: BusinessError) => { 2083 console.error("truncate file failed with error message: " + err.message + ", error code: " + err.code); 2084 }); 2085 ``` 2086 2087## fs.truncate 2088 2089truncate(file: string | number, len?: number, callback: AsyncCallback<void>): void 2090 2091截断文件内容,使用callback异步回调。 2092 2093**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2094 2095**系统能力**:SystemCapability.FileManagement.File.FileIO 2096 2097**参数:** 2098 2099| 参数名 | 类型 | 必填 | 说明 | 2100| -------- | ------------------------- | ---- | -------------------------------- | 2101| file | string \| number | 是 | 文件的应用沙箱路径或已打开的文件描述符fd。 | 2102| len | number | 否 | 文件截断后的长度,以字节为单位。默认为0。 | 2103| callback | AsyncCallback<void> | 是 | 回调函数,本调用无返回值。 | 2104 2105**错误码:** 2106 2107接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2108 2109**示例:** 2110 2111 ```ts 2112 import { BusinessError } from '@kit.BasicServicesKit'; 2113 let filePath = pathDir + "/test.txt"; 2114 let len: number = 5; 2115 fs.truncate(filePath, len, (err: BusinessError) => { 2116 if (err) { 2117 console.error("truncate failed with error message: " + err.message + ", error code: " + err.code); 2118 } else { 2119 console.info("truncate succeed"); 2120 } 2121 }); 2122 ``` 2123 2124## fs.truncateSync 2125 2126truncateSync(file: string | number, len?: number): void 2127 2128以同步方法截断文件内容。 2129 2130**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2131 2132**系统能力**:SystemCapability.FileManagement.File.FileIO 2133 2134**参数:** 2135 2136| 参数名 | 类型 | 必填 | 说明 | 2137| ------ | ------ | ---- | -------------------------------- | 2138| file | string \| number | 是 | 文件的应用沙箱路径或已打开的文件描述符fd。 | 2139| len | number | 否 | 文件截断后的长度,以字节为单位。默认为0。 | 2140 2141**错误码:** 2142 2143接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2144 2145**示例:** 2146 2147 ```ts 2148 let filePath = pathDir + "/test.txt"; 2149 let len: number = 5; 2150 fs.truncateSync(filePath, len); 2151 ``` 2152 2153## fs.readLines<sup>11+</sup> 2154 2155readLines(filePath: string, options?: Options): Promise<ReaderIterator> 2156 2157逐行读取文件文本内容,使用Promise异步返回,只支持读取utf-8格式文件。 2158 2159**系统能力**:SystemCapability.FileManagement.File.FileIO 2160 2161**参数:** 2162 2163| 参数名 | 类型 | 必填 | 说明 | 2164| -------- | ------ | ---- | ------------------------------------------------------------ | 2165| filePath | string | 是 | 文件的应用沙箱路径。 | 2166| options | [Options](#options11) | 否 | 可选项。支持以下选项:<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。| 2167 2168**返回值:** 2169 2170 | 类型 | 说明 | 2171 | --------------------- | ---------- | 2172 | Promise<[ReaderIterator](#readeriterator11)> | Promise对象。返回文件读取迭代器。 | 2173 2174**错误码:** 2175 2176接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2177 2178**示例:** 2179 2180 ```ts 2181 import { BusinessError } from '@kit.BasicServicesKit'; 2182 import { fileIo as fs, Options } from '@kit.CoreFileKit'; 2183 let filePath = pathDir + "/test.txt"; 2184 let options: Options = { 2185 encoding: 'utf-8' 2186 }; 2187 fs.readLines(filePath, options).then((readerIterator: fs.ReaderIterator) => { 2188 for (let it = readerIterator.next(); !it.done; it = readerIterator.next()) { 2189 console.info("content: " + it.value); 2190 } 2191 }).catch((err: BusinessError) => { 2192 console.error("readLines failed with error message: " + err.message + ", error code: " + err.code); 2193 }); 2194 ``` 2195 2196## fs.readLines<sup>11+</sup> 2197 2198readLines(filePath: string, options?: Options, callback: AsyncCallback<ReaderIterator>): void 2199 2200逐行读取文件文本内容,使用callback异步回调,只支持读取utf-8格式文件。 2201 2202**系统能力**:SystemCapability.FileManagement.File.FileIO 2203 2204**参数:** 2205 2206| 参数名 | 类型 | 必填 | 说明 | 2207| -------- | ------ | ---- | ------------------------------------------------------------ | 2208| filePath | string | 是 | 文件的应用沙箱路径。 | 2209| options | [Options](#options11) | 否 | 可选项。支持以下选项:<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。| 2210| callback | AsyncCallback<[ReaderIterator](#readeriterator11)> | 是 | 逐行读取文件文本内容回调。 | 2211 2212**错误码:** 2213 2214接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2215 2216**示例:** 2217 2218 ```ts 2219 import { BusinessError } from '@kit.BasicServicesKit'; 2220 import { fileIo as fs, Options } from '@kit.CoreFileKit'; 2221 let filePath = pathDir + "/test.txt"; 2222 let options: Options = { 2223 encoding: 'utf-8' 2224 }; 2225 fs.readLines(filePath, options, (err: BusinessError, readerIterator: fs.ReaderIterator) => { 2226 if (err) { 2227 console.error("readLines failed with error message: " + err.message + ", error code: " + err.code); 2228 } else { 2229 for (let it = readerIterator.next(); !it.done; it = readerIterator.next()) { 2230 console.info("content: " + it.value); 2231 } 2232 } 2233 }); 2234 ``` 2235 2236## fs.readLinesSync<sup>11+</sup> 2237 2238readLinesSync(filePath: string, options?: Options): ReaderIterator 2239 2240以同步方式逐行读取文件文本内容。 2241 2242**系统能力**:SystemCapability.FileManagement.File.FileIO 2243 2244**参数:** 2245 2246| 参数名 | 类型 | 必填 | 说明 | 2247| -------- | ------ | ---- | ------------------------------------------------------------ | 2248| filePath | string | 是 | 文件的应用沙箱路径。 | 2249| options | [Options](#options11) | 否 | 可选项。支持以下选项:<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。| 2250 2251**返回值:** 2252 2253 | 类型 | 说明 | 2254 | --------------------- | ---------- | 2255 | [ReaderIterator](#readeriterator11) | 返回文件读取迭代器。 | 2256 2257**错误码:** 2258 2259接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2260 2261**示例:** 2262 2263 ```ts 2264 import { fileIo as fs, Options } from '@kit.CoreFileKit'; 2265 let filePath = pathDir + "/test.txt"; 2266 let options: Options = { 2267 encoding: 'utf-8' 2268 }; 2269 let readerIterator = fs.readLinesSync(filePath, options); 2270 for (let it = readerIterator.next(); !it.done; it = readerIterator.next()) { 2271 console.info("content: " + it.value); 2272 } 2273 ``` 2274 2275## ReaderIterator<sup>11+</sup> 2276 2277文件读取迭代器。在调用ReaderIterator的方法前,需要先通过readLines方法(同步或异步)来构建一个ReaderIterator实例。 2278 2279### next<sup>11+</sup> 2280 2281next(): ReaderIteratorResult 2282 2283获取迭代器下一项内容。 2284 2285**系统能力**:SystemCapability.FileManagement.File.FileIO 2286 2287**返回值:** 2288 2289 | 类型 | 说明 | 2290 | --------------------- | ---------- | 2291 | [ReaderIteratorResult](#readeriteratorresult) | 文件读取迭代器返回结果。 | 2292 2293**错误码:** 2294 2295接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2296 2297> **说明**: 2298> 2299> 如果ReaderIterator读取的当前行的编码方式不是 'utf-8',接口返回错误码13900037。 2300 2301**示例:** 2302 2303 ```ts 2304 import { BusinessError } from '@kit.BasicServicesKit'; 2305 import { fileIo as fs, Options } from '@kit.CoreFileKit'; 2306 let filePath = pathDir + "/test.txt"; 2307 let options: Options = { 2308 encoding: 'utf-8' 2309 }; 2310 fs.readLines(filePath, options).then((readerIterator: fs.ReaderIterator) => { 2311 for (let it = readerIterator.next(); !it.done; it = readerIterator.next()) { 2312 console.info("content: " + it.value); 2313 } 2314 }).catch((err: BusinessError) => { 2315 console.error("readLines failed with error message: " + err.message + ", error code: " + err.code); 2316 }); 2317 ``` 2318 2319## ReaderIteratorResult 2320 2321文件读取迭代器返回结果,支持ReaderIterator接口使用。 2322 2323**系统能力**:SystemCapability.FileManagement.File.FileIO 2324 2325| 名称 | 类型 | 说明 | 2326| ----------- | --------------- | ------------------ | 2327| done | boolean | 迭代器是否已完成迭代。 | 2328| value | string | 逐行读取的文件文本内容。 | 2329 2330## fs.readText 2331 2332readText(filePath: string, options?: ReadTextOptions): Promise<string> 2333 2334基于文本方式读取文件(即直接读取文件的文本内容),使用Promise异步返回。 2335 2336**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2337 2338**系统能力**:SystemCapability.FileManagement.File.FileIO 2339 2340**参数:** 2341 2342| 参数名 | 类型 | 必填 | 说明 | 2343| -------- | ------ | ---- | ------------------------------------------------------------ | 2344| filePath | string | 是 | 文件的应用沙箱路径。 | 2345| options | [ReadTextOptions](#readtextoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读取。<br/>- length,number类型,表示期望读取数据的长度。可选,默认文件长度。<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。 | 2346 2347**返回值:** 2348 2349 | 类型 | 说明 | 2350 | --------------------- | ---------- | 2351 | Promise<string> | Promise对象。返回读取文件的内容。 | 2352 2353**错误码:** 2354 2355接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2356 2357**示例:** 2358 2359 ```ts 2360 import { BusinessError } from '@kit.BasicServicesKit'; 2361 let filePath = pathDir + "/test.txt"; 2362 fs.readText(filePath).then((str: string) => { 2363 console.info("readText succeed:" + str); 2364 }).catch((err: BusinessError) => { 2365 console.error("readText failed with error message: " + err.message + ", error code: " + err.code); 2366 }); 2367 ``` 2368 2369## fs.readText 2370 2371readText(filePath: string, options?: ReadTextOptions, callback: AsyncCallback<string>): void 2372 2373基于文本方式读取文件(即直接读取文件的文本内容),使用callback异步回调。 2374 2375**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2376 2377**系统能力**:SystemCapability.FileManagement.File.FileIO 2378 2379**参数:** 2380 2381| 参数名 | 类型 | 必填 | 说明 | 2382| -------- | --------------------------- | ---- | ------------------------------------------------------------ | 2383| filePath | string | 是 | 文件的应用沙箱路径。 | 2384| options | [ReadTextOptions](#readtextoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读取。<br/>- length,number类型,表示期望读取数据的长度。可选,默认文件长度。<br/>- encoding,string类型,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。 | 2385| callback | AsyncCallback<string> | 是 | 回调函数,返回读取文件的内容。 | 2386 2387**错误码:** 2388 2389接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2390 2391**示例:** 2392 2393 ```ts 2394 import { BusinessError } from '@kit.BasicServicesKit'; 2395 import { fileIo as fs, ReadTextOptions } from '@kit.CoreFileKit'; 2396 let filePath = pathDir + "/test.txt"; 2397 let readTextOption: ReadTextOptions = { 2398 offset: 1, 2399 length: 0, 2400 encoding: 'utf-8' 2401 }; 2402 let stat = fs.statSync(filePath); 2403 readTextOption.length = stat.size; 2404 fs.readText(filePath, readTextOption, (err: BusinessError, str: string) => { 2405 if (err) { 2406 console.error("readText failed with error message: " + err.message + ", error code: " + err.code); 2407 } else { 2408 console.info("readText succeed:" + str); 2409 } 2410 }); 2411 ``` 2412 2413## fs.readTextSync 2414 2415readTextSync(filePath: string, options?: ReadTextOptions): string 2416 2417以同步方法基于文本方式读取文件(即直接读取文件的文本内容)。 2418 2419**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2420 2421**系统能力**:SystemCapability.FileManagement.File.FileIO 2422 2423**参数:** 2424 2425| 参数名 | 类型 | 必填 | 说明 | 2426| -------- | ------ | ---- | ------------------------------------------------------------ | 2427| filePath | string | 是 | 文件的应用沙箱路径。 | 2428| options | [ReadTextOptions](#readtextoptions11) | 否 | 支持如下选项:<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读取。<br/>- length,number类型,表示期望读取数据的长度。可选,默认文件长度。<br/>- encoding,string类型,当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。 | 2429 2430**返回值:** 2431 2432 | 类型 | 说明 | 2433 | ------ | -------------------- | 2434 | string | 返回读取文件的内容。 | 2435 2436**错误码:** 2437 2438接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2439 2440**示例:** 2441 2442 ```ts 2443 import { fileIo as fs, ReadTextOptions } from '@kit.CoreFileKit'; 2444 let filePath = pathDir + "/test.txt"; 2445 let readTextOptions: ReadTextOptions = { 2446 offset: 1, 2447 length: 0, 2448 encoding: 'utf-8' 2449 }; 2450 let stat = fs.statSync(filePath); 2451 readTextOptions.length = stat.size; 2452 let str = fs.readTextSync(filePath, readTextOptions); 2453 console.info("readText succeed:" + str); 2454 ``` 2455 2456## fs.lstat 2457 2458lstat(path: string): Promise<Stat> 2459 2460获取链接文件信息,使用Promise异步返回。 2461 2462**系统能力**:SystemCapability.FileManagement.File.FileIO 2463 2464**参数:** 2465 2466| 参数名 | 类型 | 必填 | 说明 | 2467| ------ | ------ | ---- | -------------------------------------- | 2468| path | string | 是 | 文件的应用沙箱路径。 | 2469 2470**返回值:** 2471 2472 | 类型 | 说明 | 2473 | ---------------------------- | ---------- | 2474 | Promise<[Stat](#stat)> | Promise对象。返回文件对象,表示文件的具体信息,详情见stat。 | 2475 2476**错误码:** 2477 2478接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2479 2480**示例:** 2481 2482 ```ts 2483 import { BusinessError } from '@kit.BasicServicesKit'; 2484 let filePath = pathDir + "/linkToFile"; 2485 fs.lstat(filePath).then((stat: fs.Stat) => { 2486 console.info("lstat succeed, the size of file is " + stat.size); 2487 }).catch((err: BusinessError) => { 2488 console.error("lstat failed with error message: " + err.message + ", error code: " + err.code); 2489 }); 2490 ``` 2491 2492## fs.lstat 2493 2494lstat(path: string, callback: AsyncCallback<Stat>): void 2495 2496获取链接文件信息,使用callback异步回调。 2497 2498**系统能力**:SystemCapability.FileManagement.File.FileIO 2499 2500**参数:** 2501 2502| 参数名 | 类型 | 必填 | 说明 | 2503| -------- | ---------------------------------- | ---- | -------------------------------------- | 2504| path | string | 是 | 文件的应用沙箱路径。 | 2505| callback | AsyncCallback<[Stat](#stat)> | 是 | 回调函数,返回文件的具体信息。 | 2506 2507**错误码:** 2508 2509接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2510 2511**示例:** 2512 2513 ```ts 2514 import { BusinessError } from '@kit.BasicServicesKit'; 2515 let filePath = pathDir + "/linkToFile"; 2516 fs.lstat(filePath, (err: BusinessError, stat: fs.Stat) => { 2517 if (err) { 2518 console.error("lstat failed with error message: " + err.message + ", error code: " + err.code); 2519 } else { 2520 console.info("lstat succeed, the size of file is" + stat.size); 2521 } 2522 }); 2523 ``` 2524 2525## fs.lstatSync 2526 2527lstatSync(path: string): Stat 2528 2529以同步方法获取链接文件信息。 2530 2531**系统能力**:SystemCapability.FileManagement.File.FileIO 2532 2533**参数:** 2534 2535| 参数名 | 类型 | 必填 | 说明 | 2536| ------ | ------ | ---- | -------------------------------------- | 2537| path | string | 是 | 文件的应用沙箱路径。 | 2538 2539**返回值:** 2540 2541 | 类型 | 说明 | 2542 | ------------- | ---------- | 2543 | [Stat](#stat) | 表示文件的具体信息。 | 2544 2545**错误码:** 2546 2547接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2548 2549**示例:** 2550 2551 ```ts 2552 let filePath = pathDir + "/linkToFile"; 2553 let fileStat = fs.lstatSync(filePath); 2554 console.info("lstat succeed, the size of file is" + fileStat.size); 2555 ``` 2556 2557## fs.rename 2558 2559rename(oldPath: string, newPath: string): Promise<void> 2560 2561重命名文件或文件夹,使用Promise异步返回。 2562 2563> **说明:** 2564> 2565> 该接口不支持在分布式文件路径下操作。 2566 2567**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2568 2569**系统能力**:SystemCapability.FileManagement.File.FileIO 2570 2571**参数:** 2572 2573| 参数名 | 类型 | 必填 | 说明 | 2574| ------- | ------ | ---- | ---------------------------- | 2575| oldPath | string | 是 | 文件的应用沙箱原路径。 | 2576| newPath | string | 是 | 文件的应用沙箱新路径。 | 2577 2578**返回值:** 2579 2580 | 类型 | 说明 | 2581 | ------------------- | ---------------------------- | 2582 | Promise<void> | Promise对象。无返回值。 | 2583 2584**错误码:** 2585 2586接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2587 2588**示例:** 2589 2590 ```ts 2591 import { BusinessError } from '@kit.BasicServicesKit'; 2592 let srcFile = pathDir + "/test.txt"; 2593 let dstFile = pathDir + "/new.txt"; 2594 fs.rename(srcFile, dstFile).then(() => { 2595 console.info("rename succeed"); 2596 }).catch((err: BusinessError) => { 2597 console.error("rename failed with error message: " + err.message + ", error code: " + err.code); 2598 }); 2599 ``` 2600 2601## fs.rename 2602 2603rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): void 2604 2605重命名文件或文件夹,使用callback异步回调。 2606 2607> **说明:** 2608> 2609> 该接口不支持在分布式文件路径下操作。 2610 2611**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2612 2613**系统能力**:SystemCapability.FileManagement.File.FileIO 2614 2615**参数:** 2616 2617| 参数名 | 类型 | 必填 | 说明 | 2618| -------- | ------------------------- | ---- | ---------------------------- | 2619| oldPath | string | 是 | 文件的应用沙箱原路径。 | 2620| newPath | string | 是 | 文件的应用沙箱新路径。 | 2621| callback | AsyncCallback<void> | 是 | 异步重命名文件之后的回调。 | 2622 2623**错误码:** 2624 2625接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2626 2627**示例:** 2628 2629 ```ts 2630 import { BusinessError } from '@kit.BasicServicesKit'; 2631 let srcFile = pathDir + "/test.txt"; 2632 let dstFile = pathDir + "/new.txt"; 2633 fs.rename(srcFile, dstFile, (err: BusinessError) => { 2634 if (err) { 2635 console.error("rename failed with error message: " + err.message + ", error code: " + err.code); 2636 } else { 2637 console.info("rename succeed"); 2638 } 2639 }); 2640 ``` 2641 2642## fs.renameSync 2643 2644renameSync(oldPath: string, newPath: string): void 2645 2646以同步方法重命名文件或文件夹。 2647 2648> **说明:** 2649> 2650> 该接口不支持在分布式文件路径下操作。 2651 2652**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2653 2654**系统能力**:SystemCapability.FileManagement.File.FileIO 2655 2656**参数:** 2657 2658| 参数名 | 类型 | 必填 | 说明 | 2659| ------- | ------ | ---- | ---------------------------- | 2660| oldPath | string | 是 | 文件的应用沙箱原路径。 | 2661| newPath | string | 是 | 文件的应用沙箱新路径。 | 2662 2663**错误码:** 2664 2665接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2666 2667**示例:** 2668 2669 ```ts 2670 let srcFile = pathDir + "/test.txt"; 2671 let dstFile = pathDir + "/new.txt"; 2672 fs.renameSync(srcFile, dstFile); 2673 ``` 2674 2675## fs.fsync 2676 2677fsync(fd: number): Promise<void> 2678 2679将文件系统缓存数据写入磁盘,使用Promise异步返回。 2680 2681**系统能力**:SystemCapability.FileManagement.File.FileIO 2682 2683**参数:** 2684 2685 | 参数名 | 类型 | 必填 | 说明 | 2686 | ---- | ------ | ---- | ------------ | 2687 | fd | number | 是 | 已打开的文件描述符。 | 2688 2689**返回值:** 2690 2691 | 类型 | 说明 | 2692 | ------------------- | ---------------------------- | 2693 | Promise<void> | Promise对象。无返回值。 | 2694 2695**错误码:** 2696 2697接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2698 2699**示例:** 2700 2701 ```ts 2702 import { BusinessError } from '@kit.BasicServicesKit'; 2703 let filePath = pathDir + "/test.txt"; 2704 let file = fs.openSync(filePath); 2705 fs.fsync(file.fd).then(() => { 2706 console.info("sync data succeed"); 2707 }).catch((err: BusinessError) => { 2708 console.error("sync data failed with error message: " + err.message + ", error code: " + err.code); 2709 }).finally(() => { 2710 fs.closeSync(file); 2711 }); 2712 ``` 2713 2714## fs.fsync 2715 2716fsync(fd: number, callback: AsyncCallback<void>): void 2717 2718将文件系统缓存数据写入磁盘,使用callback异步回调。 2719 2720**系统能力**:SystemCapability.FileManagement.File.FileIO 2721 2722**参数:** 2723 2724 | 参数名 | 类型 | 必填 | 说明 | 2725 | -------- | ------------------------- | ---- | --------------- | 2726 | fd | number | 是 | 已打开的文件描述符。 | 2727 | Callback | AsyncCallback<void> | 是 | 异步将文件数据同步之后的回调。 | 2728 2729**错误码:** 2730 2731接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2732 2733**示例:** 2734 2735 ```ts 2736 import { BusinessError } from '@kit.BasicServicesKit'; 2737 let filePath = pathDir + "/test.txt"; 2738 let file = fs.openSync(filePath); 2739 fs.fsync(file.fd, (err: BusinessError) => { 2740 if (err) { 2741 console.error("fsync failed with error message: " + err.message + ", error code: " + err.code); 2742 } else { 2743 console.info("fsync succeed"); 2744 } 2745 fs.closeSync(file); 2746 }); 2747 ``` 2748 2749 2750## fs.fsyncSync 2751 2752fsyncSync(fd: number): void 2753 2754以同步方法将文件系统缓存数据写入磁盘。 2755 2756**系统能力**:SystemCapability.FileManagement.File.FileIO 2757 2758**参数:** 2759 2760 | 参数名 | 类型 | 必填 | 说明 | 2761 | ---- | ------ | ---- | ------------ | 2762 | fd | number | 是 | 已打开的文件描述符。 | 2763 2764**错误码:** 2765 2766接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2767 2768**示例:** 2769 2770 ```ts 2771 let filePath = pathDir + "/test.txt"; 2772 let file = fs.openSync(filePath); 2773 fs.fsyncSync(file.fd); 2774 fs.closeSync(file); 2775 ``` 2776 2777## fs.fdatasync 2778 2779fdatasync(fd: number): Promise<void> 2780 2781实现文件内容数据同步,使用Promise异步返回。 2782 2783**系统能力**:SystemCapability.FileManagement.File.FileIO 2784 2785**参数:** 2786 2787 | 参数名 | 类型 | 必填 | 说明 | 2788 | ---- | ------ | ---- | ------------ | 2789 | fd | number | 是 | 已打开的文件描述符。 | 2790 2791**返回值:** 2792 2793 | 类型 | 说明 | 2794 | ------------------- | ---------------------------- | 2795 | Promise<void> | Promise对象。无返回值。 | 2796 2797**错误码:** 2798 2799接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2800 2801**示例:** 2802 2803 ```ts 2804 import { BusinessError } from '@kit.BasicServicesKit'; 2805 let filePath = pathDir + "/test.txt"; 2806 let file = fs.openSync(filePath); 2807 fs.fdatasync(file.fd).then(() => { 2808 console.info("sync data succeed"); 2809 }).catch((err: BusinessError) => { 2810 console.error("sync data failed with error message: " + err.message + ", error code: " + err.code); 2811 }).finally(() => { 2812 fs.closeSync(file); 2813 }); 2814 ``` 2815 2816## fs.fdatasync 2817 2818fdatasync(fd: number, callback: AsyncCallback<void>): void 2819 2820实现文件内容数据同步,使用callback异步回调。 2821 2822**系统能力**:SystemCapability.FileManagement.File.FileIO 2823 2824**参数:** 2825 2826 | 参数名 | 类型 | 必填 | 说明 | 2827 | -------- | ------------------------------- | ---- | ----------------- | 2828 | fd | number | 是 | 已打开的文件描述符。 | 2829 | callback | AsyncCallback<void> | 是 | 异步将文件内容数据同步之后的回调。 | 2830 2831**错误码:** 2832 2833接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2834 2835**示例:** 2836 2837 ```ts 2838 import { BusinessError } from '@kit.BasicServicesKit'; 2839 let filePath = pathDir + "/test.txt"; 2840 let file = fs.openSync(filePath); 2841 fs.fdatasync (file.fd, (err: BusinessError) => { 2842 if (err) { 2843 console.error("fdatasync failed with error message: " + err.message + ", error code: " + err.code); 2844 } else { 2845 console.info("fdatasync succeed"); 2846 } 2847 fs.closeSync(file); 2848 }); 2849 ``` 2850 2851## fs.fdatasyncSync 2852 2853fdatasyncSync(fd: number): void 2854 2855以同步方法实现文件内容数据同步。 2856 2857**系统能力**:SystemCapability.FileManagement.File.FileIO 2858 2859**参数:** 2860 2861 | 参数名 | 类型 | 必填 | 说明 | 2862 | ---- | ------ | ---- | ------------ | 2863 | fd | number | 是 | 已打开的文件描述符。 | 2864 2865**错误码:** 2866 2867接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2868 2869**示例:** 2870 2871 ```ts 2872 let filePath = pathDir + "/test.txt"; 2873 let file = fs.openSync(filePath); 2874 fs.fdatasyncSync(file.fd); 2875 fs.closeSync(file); 2876 ``` 2877 2878## fs.symlink 2879 2880symlink(target: string, srcPath: string): Promise<void> 2881 2882基于文件路径创建符号链接,使用Promise异步返回。 2883 2884**系统能力**:SystemCapability.FileManagement.File.FileIO 2885 2886**参数:** 2887 2888| 参数名 | 类型 | 必填 | 说明 | 2889| ------- | ------ | ---- | ---------------------------- | 2890| target | string | 是 | 源文件的应用沙箱路径。 | 2891| srcPath | string | 是 | 符号链接文件的应用沙箱路径。 | 2892 2893**返回值:** 2894 2895 | 类型 | 说明 | 2896 | ------------------- | ---------------------------- | 2897 | Promise<void> | Promise对象。无返回值。 | 2898 2899**错误码:** 2900 2901接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2902 2903**示例:** 2904 2905 ```ts 2906 import { BusinessError } from '@kit.BasicServicesKit'; 2907 let srcFile = pathDir + "/test.txt"; 2908 let dstFile = pathDir + "/test"; 2909 fs.symlink(srcFile, dstFile).then(() => { 2910 console.info("symlink succeed"); 2911 }).catch((err: BusinessError) => { 2912 console.error("symlink failed with error message: " + err.message + ", error code: " + err.code); 2913 }); 2914 ``` 2915 2916 2917## fs.symlink 2918symlink(target: string, srcPath: string, callback: AsyncCallback<void>): void 2919 2920基于文件路径创建符号链接,使用callback异步回调。 2921 2922**系统能力**:SystemCapability.FileManagement.File.FileIO 2923 2924**参数:** 2925 2926| 参数名 | 类型 | 必填 | 说明 | 2927| -------- | ------------------------- | ---- | -------------------------------- | 2928| target | string | 是 | 源文件的应用沙箱路径。 | 2929| srcPath | string | 是 | 符号链接文件的应用沙箱路径。 | 2930| callback | AsyncCallback<void> | 是 | 异步创建符号链接信息之后的回调。 | 2931 2932**错误码:** 2933 2934接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2935 2936**示例:** 2937 2938 ```ts 2939 import { BusinessError } from '@kit.BasicServicesKit'; 2940 let srcFile = pathDir + "/test.txt"; 2941 let dstFile = pathDir + "/test"; 2942 fs.symlink(srcFile, dstFile, (err: BusinessError) => { 2943 if (err) { 2944 console.error("symlink failed with error message: " + err.message + ", error code: " + err.code); 2945 } else { 2946 console.info("symlink succeed"); 2947 } 2948 }); 2949 ``` 2950 2951## fs.symlinkSync 2952 2953symlinkSync(target: string, srcPath: string): void 2954 2955以同步的方法基于文件路径创建符号链接。 2956 2957**系统能力**:SystemCapability.FileManagement.File.FileIO 2958 2959**参数:** 2960 2961| 参数名 | 类型 | 必填 | 说明 | 2962| ------- | ------ | ---- | ---------------------------- | 2963| target | string | 是 | 源文件的应用沙箱路径。 | 2964| srcPath | string | 是 | 符号链接文件的应用沙箱路径。 | 2965 2966**错误码:** 2967 2968接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 2969 2970**示例:** 2971 2972 ```ts 2973 let srcFile = pathDir + "/test.txt"; 2974 let dstFile = pathDir + "/test"; 2975 fs.symlinkSync(srcFile, dstFile); 2976 ``` 2977 2978## fs.listFile 2979listFile(path: string, options?: ListFileOptions): Promise<string[]> 2980 2981列出文件夹下所有文件名。支持递归列出所有文件名(包含子目录下),支持文件过滤。使用Promise异步返回。 2982 2983**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 2984 2985**系统能力**:SystemCapability.FileManagement.File.FileIO 2986 2987**参数:** 2988 2989 | 参数名 | 类型 | 必填 | 说明 | 2990 | ------ | ------ | ---- | --------------------------- | 2991 | path | string | 是 | 文件夹的应用沙箱路径。 | 2992 | options | [ListFileOptions](#listfileoptions11) | 否 | 文件过滤选项。默认不进行过滤。 | 2993 2994 2995**返回值:** 2996 2997 | 类型 | 说明 | 2998 | --------------------- | ---------- | 2999 | Promise<string[]> | Promise对象。返回文件名数组。 | 3000 3001**错误码:** 3002 3003接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3004 3005**示例:** 3006 3007 ```ts 3008 import { BusinessError } from '@kit.BasicServicesKit'; 3009 import { fileIo as fs, Filter, ListFileOptions } from '@kit.CoreFileKit'; 3010 let listFileOption: ListFileOptions = { 3011 recursion: false, 3012 listNum: 0, 3013 filter: { 3014 suffix: [".png", ".jpg", ".jpeg"], 3015 displayName: ["*abc", "efg*"], 3016 fileSizeOver: 1024 3017 } 3018 } 3019 fs.listFile(pathDir, listFileOption).then((filenames: Array<string>) => { 3020 console.info("listFile succeed"); 3021 for (let i = 0; i < filenames.length; i++) { 3022 console.info("fileName: %s", filenames[i]); 3023 } 3024 }).catch((err: BusinessError) => { 3025 console.error("list file failed with error message: " + err.message + ", error code: " + err.code); 3026 }); 3027 ``` 3028 3029## fs.listFile 3030listFile(path: string, options?: ListFileOptions, callback: AsyncCallback<string[]>): void 3031 3032列出文件夹下所有文件名。支持递归列出所有文件名(包含子目录下),支持文件过滤。使用Callback异步回调。 3033 3034**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 3035 3036**系统能力**:SystemCapability.FileManagement.File.FileIO 3037 3038**参数:** 3039 3040 | 参数名 | 类型 | 必填 | 说明 | 3041 | ------ | ------ | ---- | --------------------------- | 3042 | path | string | 是 | 文件夹的应用沙箱路径。 | 3043 | options | [ListFileOptions](#listfileoptions11) | 否 | 文件过滤选项。默认不进行过滤。 | 3044 | callback | AsyncCallback<string[]> | 是 | 异步列出文件名数组之后的回调。 | 3045 3046 3047**错误码:** 3048 3049接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3050 3051**示例:** 3052 3053 ```ts 3054 import { BusinessError } from '@kit.BasicServicesKit'; 3055 import { fileIo as fs, Filter, ListFileOptions } from '@kit.CoreFileKit'; 3056 let listFileOption: ListFileOptions = { 3057 recursion: false, 3058 listNum: 0, 3059 filter: { 3060 suffix: [".png", ".jpg", ".jpeg"], 3061 displayName: ["*abc", "efg*"], 3062 fileSizeOver: 1024 3063 } 3064 }; 3065 fs.listFile(pathDir, listFileOption, (err: BusinessError, filenames: Array<string>) => { 3066 if (err) { 3067 console.error("list file failed with error message: " + err.message + ", error code: " + err.code); 3068 } else { 3069 console.info("listFile succeed"); 3070 for (let i = 0; i < filenames.length; i++) { 3071 console.info("filename: %s", filenames[i]); 3072 } 3073 } 3074 }); 3075 ``` 3076 3077## fs.listFileSync 3078 3079listFileSync(path: string, options?: ListFileOptions): string[] 3080 3081以同步方式列出文件夹下所有文件名。支持递归列出所有文件名(包含子目录下),支持文件过滤。 3082 3083**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 3084 3085**系统能力**:SystemCapability.FileManagement.File.FileIO 3086 3087**参数:** 3088 3089 | 参数名 | 类型 | 必填 | 说明 | 3090 | ------ | ------ | ---- | --------------------------- | 3091 | path | string | 是 | 文件夹的应用沙箱路径。 | 3092 | options | [ListFileOptions](#listfileoptions11) | 否 | 文件过滤选项。默认不进行过滤。 | 3093 3094 3095**返回值:** 3096 3097 | 类型 | 说明 | 3098 | --------------------- | ---------- | 3099 | string[] | 返回文件名数组。 | 3100 3101**错误码:** 3102 3103接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3104 3105**示例:** 3106 3107 ```ts 3108 import { fileIo as fs, Filter, ListFileOptions} from '@kit.CoreFileKit'; 3109 let listFileOption: ListFileOptions = { 3110 recursion: false, 3111 listNum: 0, 3112 filter: { 3113 suffix: [".png", ".jpg", ".jpeg"], 3114 displayName: ["*abc", "efg*"], 3115 fileSizeOver: 1024 3116 } 3117 }; 3118 let filenames = fs.listFileSync(pathDir, listFileOption); 3119 console.info("listFile succeed"); 3120 for (let i = 0; i < filenames.length; i++) { 3121 console.info("filename: %s", filenames[i]); 3122 } 3123 ``` 3124 3125## fs.lseek<sup>11+</sup> 3126 3127lseek(fd: number, offset: number, whence?: WhenceType): number 3128 3129调整文件偏置指针位置。 3130 3131**系统能力**:SystemCapability.FileManagement.File.FileIO 3132 3133**参数:** 3134 3135 | 参数名 | 类型 | 必填 | 说明 | 3136 | ------ | ------ | ---- | --------------------------- | 3137 | fd | number | 是 | 文件描述符。 | 3138 | offset | number | 是 | 相对偏移位置,单位为字节。 | 3139 | whence | [WhenceType](#whencetype11) | 否 | 偏移指针相对位置类型。 | 3140 3141**返回值:** 3142 3143 | 类型 | 说明 | 3144 | --------------------- | ---------- | 3145 | number | 当前文件偏置指针位置(相对于文件头的偏移量,单位为字节)。 | 3146 3147**错误码:** 3148 3149接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3150 3151**示例:** 3152 3153 ```ts 3154 let filePath = pathDir + "/test.txt"; 3155 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3156 console.info('The current offset is at ' + fs.lseek(file.fd, 5, fs.WhenceType.SEEK_SET)); 3157 fs.closeSync(file); 3158 ``` 3159 3160## fs.moveDir<sup>10+</sup> 3161 3162moveDir(src: string, dest: string, mode?: number): Promise\<void> 3163 3164移动源文件夹至目标路径下,使用Promise异步返回。 3165 3166> **说明:** 3167> 3168> 该接口不支持在分布式文件路径下操作。 3169 3170**系统能力**:SystemCapability.FileManagement.File.FileIO 3171 3172**参数:** 3173 3174 | 参数名 | 类型 | 必填 | 说明 | 3175 | ------ | ------ | ---- | --------------------------- | 3176 | src | string | 是 | 源文件夹的应用沙箱路径。 | 3177 | dest | string | 是 | 目标文件夹的应用沙箱路径。 | 3178 | mode | number | 否 | 移动模式。默认mode为0。<br/>- mode为0,文件夹级别抛异常。若目标文件夹下存在与源文件夹名冲突的非空文件夹,则抛出异常。<br/>- mode为1,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为2,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。<br/>- mode为3,文件夹级别强制覆盖。移动源文件夹至目标文件夹下,目标文件夹下移动的文件夹内容与源文件夹完全一致。若目标文件夹下存在与源文件夹名冲突的文件夹,该文件夹下所有原始文件将不会保留。| 3179 3180**返回值:** 3181 3182 | 类型 | 说明 | 3183 | ------------------- | ---------------------------- | 3184 | Promise<void> | Promise对象。无返回值。 | 3185 3186**错误码:** 3187 3188接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3189 3190**示例:** 3191 3192 ```ts 3193 import { BusinessError } from '@kit.BasicServicesKit'; 3194 // move directory from srcPath to destPath 3195 let srcPath = pathDir + "/srcDir/"; 3196 let destPath = pathDir + "/destDir/"; 3197 fs.moveDir(srcPath, destPath, 1).then(() => { 3198 console.info("move directory succeed"); 3199 }).catch((err: BusinessError) => { 3200 console.error("move directory failed with error message: " + err.message + ", error code: " + err.code); 3201 }); 3202 ``` 3203 3204## fs.moveDir<sup>10+</sup> 3205 3206moveDir(src: string, dest: string, mode: number, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 3207 3208移动源文件夹至目标路径下,支持设置移动模式。使用callback异步回调。 3209 3210> **说明:** 3211> 3212> 该接口不支持在分布式文件路径下操作。 3213 3214**系统能力**:SystemCapability.FileManagement.File.FileIO 3215 3216**参数:** 3217 3218 | 参数名 | 类型 | 必填 | 说明 | 3219 | ------ | ------ | ---- | --------------------------- | 3220 | src | string | 是 | 源文件夹的应用沙箱路径。 | 3221 | dest | string | 是 | 目标文件夹的应用沙箱路径。 | 3222 | mode | number | 是 | 移动模式。默认mode为0。<br/>- mode为0,文件夹级别抛异常。若目标文件夹下存在与源文件夹名冲突的文件夹,则抛出异常。<br/>- mode为1,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为2,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。<br/>- mode为3,文件夹级别强制覆盖。移动源文件夹至目标文件夹下,目标文件夹下移动的文件夹内容与源文件夹完全一致。若目标文件夹下存在与源文件夹名冲突的文件夹,该文件夹下所有原始文件将不会保留。| 3223 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | 是 | 异步移动文件夹之后的回调。 | 3224 3225**错误码:** 3226 3227接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3228 3229**示例:** 3230 3231 ```ts 3232 import { BusinessError } from '@kit.BasicServicesKit'; 3233 import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 3234 // move directory from srcPath to destPath 3235 let srcPath = pathDir + "/srcDir/"; 3236 let destPath = pathDir + "/destDir/"; 3237 fs.moveDir(srcPath, destPath, 1, (err: BusinessError<Array<ConflictFiles>>) => { 3238 if (err && err.code == 13900015 && err.data?.length !== undefined) { 3239 for (let i = 0; i < err.data.length; i++) { 3240 console.error("move directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 3241 } 3242 } else if (err) { 3243 console.error("move directory failed with error message: " + err.message + ", error code: " + err.code); 3244 } else { 3245 console.info("move directory succeed"); 3246 } 3247 }); 3248 ``` 3249 3250 ## fs.moveDir<sup>10+</sup> 3251 3252moveDir(src: string, dest: string, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 3253 3254移动源文件夹至目标路径下。使用callback异步回调。 3255 3256移动模式为文件夹级别抛异常。当目标文件夹下存在与源文件夹名冲突的文件夹,则抛出异常。 3257 3258> **说明:** 3259> 3260> 该接口不支持在分布式文件路径下操作。 3261 3262**系统能力**:SystemCapability.FileManagement.File.FileIO 3263 3264**参数:** 3265 3266 | 参数名 | 类型 | 必填 | 说明 | 3267 | ------ | ------ | ---- | --------------------------- | 3268 | src | string | 是 | 源文件夹的应用沙箱路径。 | 3269 | dest | string | 是 | 目标文件夹的应用沙箱路径。 | 3270 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | 是 | 异步移动文件夹之后的回调。 | 3271 3272**错误码:** 3273 3274接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3275 3276**示例:** 3277 3278 ```ts 3279 import { BusinessError } from '@kit.BasicServicesKit'; 3280 import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 3281 // move directory from srcPath to destPath 3282 let srcPath = pathDir + "/srcDir/"; 3283 let destPath = pathDir + "/destDir/"; 3284 fs.moveDir(srcPath, destPath, (err: BusinessError<Array<ConflictFiles>>) => { 3285 if (err && err.code == 13900015 && err.data?.length !== undefined) { 3286 for (let i = 0; i < err.data.length; i++) { 3287 console.error("move directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 3288 } 3289 } else if (err) { 3290 console.error("move directory failed with error message: " + err.message + ", error code: " + err.code); 3291 } else { 3292 console.info("move directory succeed"); 3293 } 3294 }); 3295 ``` 3296 3297## fs.moveDirSync<sup>10+</sup> 3298 3299moveDirSync(src: string, dest: string, mode?: number): void 3300 3301以同步方法移动源文件夹至目标路径下。 3302 3303> **说明:** 3304> 3305> 该接口不支持在分布式文件路径下操作。 3306 3307**系统能力**:SystemCapability.FileManagement.File.FileIO 3308 3309**参数:** 3310 3311 | 参数名 | 类型 | 必填 | 说明 | 3312 | ------ | ------ | ---- | --------------------------- | 3313 | src | string | 是 | 源文件夹的应用沙箱路径。 | 3314 | dest | string | 是 | 目标文件夹的应用沙箱路径。 | 3315 | mode | number | 否 | 移动模式。默认mode为0。<br/>- mode为0,文件夹级别抛异常。若目标文件夹下存在与源文件夹名冲突的文件夹,则抛出异常。<br/>- mode为1,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>- mode为2,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。<br/>- mode为3,文件夹级别强制覆盖。移动源文件夹至目标文件夹下,目标文件夹下移动的文件夹内容与源文件夹完全一致。若目标文件夹下存在与源文件夹名冲突的文件夹,该文件夹下所有原始文件将不会保留。| 3316 3317**错误码:** 3318 3319接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3320 3321**示例:** 3322 3323 ```ts 3324 import { BusinessError } from '@kit.BasicServicesKit'; 3325import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit'; 3326// move directory from srcPath to destPath 3327let srcPath = pathDir + "/srcDir/"; 3328let destPath = pathDir + "/destDir/"; 3329try { 3330 fs.moveDirSync(srcPath, destPath, 1); 3331 console.info("move directory succeed"); 3332} catch (error) { 3333 let err: BusinessError<Array<ConflictFiles>> = error as BusinessError<Array<ConflictFiles>>; 3334 if (err.code == 13900015 && err.data?.length !== undefined) { 3335 for (let i = 0; i < err.data.length; i++) { 3336 console.error("move directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile); 3337 } 3338 } else { 3339 console.error("move directory failed with error message: " + err.message + ", error code: " + err.code); 3340 } 3341} 3342 ``` 3343 3344## fs.moveFile 3345 3346moveFile(src: string, dest: string, mode?: number): Promise\<void> 3347 3348移动文件,使用Promise异步返回。 3349 3350> **说明:** 3351> 3352> 该接口不支持在分布式文件路径下操作。 3353 3354**系统能力**:SystemCapability.FileManagement.File.FileIO 3355 3356**参数:** 3357 3358 | 参数名 | 类型 | 必填 | 说明 | 3359 | ------ | ------ | ---- | --------------------------- | 3360 | src | string | 是 | 源文件的应用沙箱路径。 | 3361 | dest | string | 是 | 目的文件的应用沙箱路径。 | 3362 | mode | number | 否 | 移动模式。若mode为0,移动位置存在同名文件时,强制移动覆盖。若mode为1,移动位置存在同名文件时,抛出异常。默认为0。 | 3363 3364**返回值:** 3365 3366 | 类型 | 说明 | 3367 | ------------------- | ---------------------------- | 3368 | Promise<void> | Promise对象。无返回值。 | 3369 3370**错误码:** 3371 3372接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3373 3374**示例:** 3375 3376 ```ts 3377 import { BusinessError } from '@kit.BasicServicesKit'; 3378 let srcPath = pathDir + "/source.txt"; 3379 let destPath = pathDir + "/dest.txt"; 3380 fs.moveFile(srcPath, destPath, 0).then(() => { 3381 console.info("move file succeed"); 3382 }).catch((err: BusinessError) => { 3383 console.error("move file failed with error message: " + err.message + ", error code: " + err.code); 3384 }); 3385 ``` 3386 3387## fs.moveFile 3388 3389moveFile(src: string, dest: string, mode: number, callback: AsyncCallback\<void>): void 3390 3391移动文件,支持设置移动模式。使用callback异步回调。 3392 3393> **说明:** 3394> 3395> 该接口不支持在分布式文件路径下操作。 3396 3397**系统能力**:SystemCapability.FileManagement.File.FileIO 3398 3399**参数:** 3400 3401 | 参数名 | 类型 | 必填 | 说明 | 3402 | ------ | ------ | ---- | --------------------------- | 3403 | src | string | 是 | 源文件的应用沙箱路径。 | 3404 | dest | string | 是 | 目的文件的应用沙箱路径。 | 3405 | mode | number | 是 | 移动模式。若mode为0,移动位置存在同名文件时,强制移动覆盖。若mode为1,移动位置存在同名文件时,抛出异常。默认为0。 | 3406 | callback | AsyncCallback<void> | 是 | 异步移动文件之后的回调。 | 3407 3408**错误码:** 3409 3410接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3411 3412**示例:** 3413 3414 ```ts 3415 import { BusinessError } from '@kit.BasicServicesKit'; 3416 let srcPath = pathDir + "/source.txt"; 3417 let destPath = pathDir + "/dest.txt"; 3418 fs.moveFile(srcPath, destPath, 0, (err: BusinessError) => { 3419 if (err) { 3420 console.error("move file failed with error message: " + err.message + ", error code: " + err.code); 3421 } else { 3422 console.info("move file succeed"); 3423 } 3424 }); 3425 ``` 3426 3427## fs.moveFile 3428 3429moveFile(src: string, dest: string, callback: AsyncCallback\<void>): void 3430 3431移动文件。当移动位置存在同名文件时,将强制移动覆盖。使用callback异步回调。 3432 3433> **说明:** 3434> 3435> 该接口不支持在分布式文件路径下操作。 3436 3437**系统能力**:SystemCapability.FileManagement.File.FileIO 3438 3439**参数:** 3440 3441 | 参数名 | 类型 | 必填 | 说明 | 3442 | ------ | ------ | ---- | --------------------------- | 3443 | src | string | 是 | 源文件的应用沙箱路径。 | 3444 | dest | string | 是 | 目的文件的应用沙箱路径。 | 3445 | callback | AsyncCallback<void> | 是 | 异步移动文件之后的回调。 | 3446 3447**错误码:** 3448 3449接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3450 3451**示例:** 3452 3453 ```ts 3454 import { BusinessError } from '@kit.BasicServicesKit'; 3455 let srcPath = pathDir + "/source.txt"; 3456 let destPath = pathDir + "/dest.txt"; 3457 fs.moveFile(srcPath, destPath, (err: BusinessError) => { 3458 if (err) { 3459 console.error("move file failed with error message: " + err.message + ", error code: " + err.code); 3460 } else { 3461 console.info("move file succeed"); 3462 } 3463 }); 3464 ``` 3465 3466## fs.moveFileSync 3467 3468moveFileSync(src: string, dest: string, mode?: number): void 3469 3470以同步方式移动文件。 3471 3472> **说明:** 3473> 3474> 该接口不支持在分布式文件路径下操作。 3475 3476**系统能力**:SystemCapability.FileManagement.File.FileIO 3477 3478**参数:** 3479 3480 | 参数名 | 类型 | 必填 | 说明 | 3481 | ------ | ------ | ---- | --------------------------- | 3482 | src | string | 是 | 源文件的应用沙箱路径。 | 3483 | dest | string | 是 | 目的文件的应用沙箱路径。 | 3484 | mode | number | 否 | 移动模式。若mode为0,移动位置存在同名文件时,强制移动覆盖。若mode为1,移动位置存在同名文件时,抛出异常。默认为0。 | 3485 3486**错误码:** 3487 3488接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3489 3490**示例:** 3491 3492 ```ts 3493 let srcPath = pathDir + "/source.txt"; 3494 let destPath = pathDir + "/dest.txt"; 3495 fs.moveFileSync(srcPath, destPath, 0); 3496 console.info("move file succeed"); 3497 ``` 3498 3499## fs.mkdtemp 3500 3501mkdtemp(prefix: string): Promise<string> 3502 3503创建临时目录,使用Promise异步返回。 3504 3505**系统能力**:SystemCapability.FileManagement.File.FileIO 3506 3507**参数:** 3508 3509 | 参数名 | 类型 | 必填 | 说明 | 3510 | ------ | ------ | ---- | --------------------------- | 3511 | prefix | string | 是 | 指定目录路径,命名时需要以"XXXXXX"作为结尾。路径末尾的"XXXXXX"字符串将被替换为随机字符,以创建唯一的目录名。 | 3512 3513**返回值:** 3514 3515 | 类型 | 说明 | 3516 | --------------------- | ---------- | 3517 | Promise<string> | Promise对象。返回生成的唯一目录路径。 | 3518 3519**错误码:** 3520 3521接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3522 3523**示例:** 3524 3525 ```ts 3526 import { BusinessError } from '@kit.BasicServicesKit'; 3527 fs.mkdtemp(pathDir + "/XXXXXX").then((dir: string) => { 3528 console.info("mkdtemp succeed:" + dir); 3529 }).catch((err: BusinessError) => { 3530 console.error("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); 3531 }); 3532 ``` 3533 3534## fs.mkdtemp 3535 3536mkdtemp(prefix: string, callback: AsyncCallback<string>): void 3537 3538创建临时目录,使用callback异步回调。 3539 3540**系统能力**:SystemCapability.FileManagement.File.FileIO 3541 3542**参数:** 3543 3544 | 参数名 | 类型 | 必填 | 说明 | 3545 | -------- | --------------------------- | ---- | --------------------------- | 3546 | prefix | string | 是 | 指定目录路径,命名时需要以"XXXXXX"作为结尾。路径末尾的"XXXXXX"字符串将被替换为随机字符,以创建唯一的目录名。 | 3547 | callback | AsyncCallback<string> | 是 | 异步创建临时目录之后的回调。 | 3548 3549**错误码:** 3550 3551接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3552 3553**示例:** 3554 3555 ```ts 3556 import { BusinessError } from '@kit.BasicServicesKit'; 3557 fs.mkdtemp(pathDir + "/XXXXXX", (err: BusinessError, res: string) => { 3558 if (err) { 3559 console.error("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); 3560 } else { 3561 console.info("mkdtemp succeed"); 3562 } 3563 }); 3564 ``` 3565 3566## fs.mkdtempSync 3567 3568mkdtempSync(prefix: string): string 3569 3570以同步的方法创建临时目录。 3571 3572**系统能力**:SystemCapability.FileManagement.File.FileIO 3573 3574**参数:** 3575 3576 | 参数名 | 类型 | 必填 | 说明 | 3577 | ------ | ------ | ---- | --------------------------- | 3578 | prefix | string | 是 | 指定目录路径,命名时需要以"XXXXXX"作为结尾。路径末尾的"XXXXXX"字符串将被替换为随机字符,以创建唯一的目录名。 | 3579 3580**返回值:** 3581 3582 | 类型 | 说明 | 3583 | ------ | ---------- | 3584 | string | 产生的唯一目录路径。 | 3585 3586**错误码:** 3587 3588接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3589 3590**示例:** 3591 3592 ```ts 3593 let res = fs.mkdtempSync(pathDir + "/XXXXXX"); 3594 ``` 3595 3596## fs.utimes<sup>11+</sup> 3597 3598utimes(path: string, mtime: number): void 3599 3600修改文件最近访问时间属性。 3601 3602**系统能力**:SystemCapability.FileManagement.File.FileIO 3603 3604**参数:** 3605| 参数名 | 类型 | 必填 | 说明 | 3606| ------------ | ------ | ------ | ------------------------------------------------------------ | 3607| path | string | 是 | 文件的应用沙箱路径。 | 3608| mtime | number | 是 | 待更新的时间戳。自1970年1月1日起至目标时间的毫秒数。仅支持修改文件最近访问时间属性。 | 3609 3610**错误码:** 3611 3612接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3613 3614**示例:** 3615 3616 ```ts 3617 let filePath = pathDir + "/test.txt"; 3618 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3619 fs.writeSync(file.fd, 'test data'); 3620 fs.closeSync(file); 3621 fs.utimes(filePath, new Date().getTime()); 3622 ``` 3623 3624## fs.createRandomAccessFile<sup>10+</sup> 3625 3626createRandomAccessFile(file: string | File, mode?: number): Promise<RandomAccessFile> 3627 3628基于文件路径或文件对象创建RandomAccessFile文件对象,使用Promise异步返回。 3629 3630**系统能力**:SystemCapability.FileManagement.File.FileIO 3631 3632**参数:** 3633| 参数名 | 类型 | 必填 | 说明 | 3634| ------------ | ------ | ------ | ------------------------------------------------------------ | 3635| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3636| mode | number | 否 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3637 3638**返回值:** 3639 3640 | 类型 | 说明 | 3641 | --------------------------------- | --------- | 3642 | Promise<[RandomAccessFile](#randomaccessfile)> | Promise对象。返回RandomAccessFile文件对象的结果。 | 3643 3644**错误码:** 3645 3646接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3647 3648**示例:** 3649 3650 ```ts 3651 import { BusinessError } from '@kit.BasicServicesKit'; 3652 let filePath = pathDir + "/test.txt"; 3653 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3654 fs.createRandomAccessFile(file).then((randomAccessFile: fs.RandomAccessFile) => { 3655 console.info("randomAccessFile fd: " + randomAccessFile.fd); 3656 randomAccessFile.close(); 3657 }).catch((err: BusinessError) => { 3658 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3659 }).finally(() => { 3660 fs.closeSync(file); 3661 }); 3662 ``` 3663 3664## fs.createRandomAccessFile<sup>10+</sup> 3665 3666createRandomAccessFile(file: string | File, callback: AsyncCallback<RandomAccessFile>): void 3667 3668基于文件路径或文件对象,以只读方式创建RandomAccessFile文件对象,使用callback异步回调。 3669 3670**系统能力**:SystemCapability.FileManagement.File.FileIO 3671 3672**参数:** 3673 3674| 参数名 | 类型 | 必填 | 说明 | 3675| ------------ | ------ | ------ | ------------------------------------------------------------ | 3676| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3677| callback | AsyncCallback<[RandomAccessFile](#randomaccessfile)> | 是 | 异步创建RandomAccessFile对象之后的回调。 | 3678 3679**错误码:** 3680 3681接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3682 3683**示例:** 3684 ```ts 3685 import { BusinessError } from '@kit.BasicServicesKit'; 3686 let filePath = pathDir + "/test.txt"; 3687 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3688 fs.createRandomAccessFile(file, (err: BusinessError, randomAccessFile: fs.RandomAccessFile) => { 3689 if (err) { 3690 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3691 } else { 3692 console.info("randomAccessFile fd: " + randomAccessFile.fd); 3693 randomAccessFile.close(); 3694 } 3695 fs.closeSync(file); 3696 }); 3697 ``` 3698 3699 ## fs.createRandomAccessFile<sup>10+</sup> 3700 3701createRandomAccessFile(file: string | File, mode: number, callback: AsyncCallback<RandomAccessFile>): void 3702 3703基于文件路径或文件对象创建RandomAccessFile文件对象。使用callback异步回调。 3704 3705**系统能力**:SystemCapability.FileManagement.File.FileIO 3706 3707**参数:** 3708 3709| 参数名 | 类型 | 必填 | 说明 | 3710| ------------ | ------ | ------ | ------------------------------------------------------------ | 3711| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3712| mode | number | 是 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3713| callback | AsyncCallback<[RandomAccessFile](#randomaccessfile)> | 是 | 异步创建RandomAccessFile对象之后的回调。 | 3714 3715**错误码:** 3716 3717接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3718 3719**示例:** 3720 ```ts 3721 import { BusinessError } from '@kit.BasicServicesKit'; 3722 let filePath = pathDir + "/test.txt"; 3723 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3724 fs.createRandomAccessFile(file, fs.OpenMode.READ_ONLY, (err: BusinessError, randomAccessFile: fs.RandomAccessFile) => { 3725 if (err) { 3726 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3727 } else { 3728 console.info("randomAccessFile fd: " + randomAccessFile.fd); 3729 randomAccessFile.close(); 3730 } 3731 fs.closeSync(file); 3732 }); 3733 ``` 3734 3735## fs.createRandomAccessFile<sup>12+</sup> 3736 3737createRandomAccessFile(file: string | File, mode?: number, options?: RandomAccessFileOptions): Promise<RandomAccessFile> 3738 3739基于文件路径或文件对象创建RandomAccessFile文件对象。使用Promise异步返回。 3740 3741**系统能力**:SystemCapability.FileManagement.File.FileIO 3742 3743**参数:** 3744 3745| 参数名 | 类型 | 必填 | 说明 | 3746| ------------ | ------ | ------ | ------------------------------------------------------------ | 3747| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3748| mode | number | 否 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3749|options|[RandomAccessFileOptions](#randomaccessfileoptions12)|否|支持如下选项:<br/>- start,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- end,number类型,表示期望读取结束的位置。可选,默认文件末尾。| 3750 3751**返回值:** 3752 3753 | 类型 | 说明 | 3754 | --------------------------------- | --------- | 3755 | Promise<[RandomAccessFile](#randomaccessfile)> | Promise对象。返回RandomAccessFile文件对象的结果。 | 3756 3757**错误码:** 3758 3759接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3760 3761```ts 3762import { BusinessError } from '@kit.BasicServicesKit'; 3763let filePath = pathDir + "/test.txt"; 3764fs.createRandomAccessFile(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE, { start: 10, end: 100 }) 3765 .then((randomAccessFile: fs.RandomAccessFile) => { 3766 console.info("randomAccessFile fd: " + randomAccessFile.fd); 3767 randomAccessFile.close(); 3768 }) 3769 .catch((err: BusinessError) => { 3770 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3771 }); 3772``` 3773 3774 3775## fs.createRandomAccessFileSync<sup>10+</sup> 3776 3777createRandomAccessFileSync(file: string | File, mode?: number): RandomAccessFile 3778 3779基于文件路径或文件对象创建RandomAccessFile文件对象。 3780 3781**系统能力**:SystemCapability.FileManagement.File.FileIO 3782 3783**参数:** 3784 3785| 参数名 | 类型 | 必填 | 说明 | 3786| ------------ | ------ | ------ | ------------------------------------------------------------ | 3787| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3788| mode | number | 否 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3789 3790**返回值:** 3791 3792 | 类型 | 说明 | 3793 | ------------------ | --------- | 3794 | [RandomAccessFile](#randomaccessfile) | 返回RandomAccessFile文件对象。 | 3795 3796**错误码:** 3797 3798接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3799 3800**示例:** 3801 3802 ```ts 3803 let filePath = pathDir + "/test.txt"; 3804 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3805 let randomAccessFile = fs.createRandomAccessFileSync(file); 3806 randomAccessFile.close(); 3807 ``` 3808 3809## fs.createRandomAccessFileSync<sup>12+</sup> 3810 3811createRandomAccessFileSync(file: string | File, mode?: number, 3812 options?: RandomAccessFileOptions): RandomAccessFile; 3813 3814基于文件路径或文件对象创建RandomAccessFile文件对象。 3815 3816**系统能力**:SystemCapability.FileManagement.File.FileIO 3817 3818**参数:** 3819 3820| 参数名 | 类型 | 必填 | 说明 | 3821| ------------ | ------ | ------ | ------------------------------------------------------------ | 3822| file | string \| [File](#file) | 是 | 文件的应用沙箱路径或已打开的File对象。 | 3823| mode | number | 否 | 创建文件RandomAccessFile对象的[选项](#openmode),仅当传入文件沙箱路径时生效,必须指定如下选项中的一个,默认以只读方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读创建。<br/>- OpenMode.WRITE_ONLY(0o1):只写创建。<br/>- OpenMode.READ_WRITE(0o2):读写创建。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果RandomAccessFile对象存在且对应文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到RandomAccessFile对象末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式创建RandomAccessFile对象。 | 3824|options|[RandomAccessFileOptions](#randomaccessfileoptions12)|否|支持如下选项:<br/>- start,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- end,number类型,表示期望读取结束的位置。可选,默认文件末尾。| 3825 3826**返回值:** 3827 3828 | 类型 | 说明 | 3829 | ------------------ | --------- | 3830 | [RandomAccessFile](#randomaccessfile) | 返回RandomAccessFile文件对象。 | 3831 3832**错误码:** 3833 3834接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3835 3836**示例:** 3837 3838 ```ts 3839 let filePath = pathDir + "/test.txt"; 3840 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE, 3841 { start: 10, end: 100 }); 3842 randomAccessFile.close(); 3843 ``` 3844 3845## fs.createStream 3846 3847createStream(path: string, mode: string): Promise<Stream> 3848 3849基于文件路径创建文件流,使用Promise异步返回。需要配合[Stream](#stream)中的close()函数关闭文件流。 3850 3851**系统能力**:SystemCapability.FileManagement.File.FileIO 3852 3853**参数:** 3854 3855| 参数名 | 类型 | 必填 | 说明 | 3856| ------ | ------ | ---- | ------------------------------------------------------------ | 3857| path | string | 是 | 文件的应用沙箱路径。 | 3858| mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 3859 3860**返回值:** 3861 3862 | 类型 | 说明 | 3863 | --------------------------------- | --------- | 3864 | Promise<[Stream](#stream)> | Promise对象。返回文件流的结果。 | 3865 3866**错误码:** 3867 3868接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3869 3870**示例:** 3871 3872 ```ts 3873 import { BusinessError } from '@kit.BasicServicesKit'; 3874 let filePath = pathDir + "/test.txt"; 3875 fs.createStream(filePath, "a+").then((stream: fs.Stream) => { 3876 stream.closeSync(); 3877 console.info("createStream succeed"); 3878 }).catch((err: BusinessError) => { 3879 console.error("createStream failed with error message: " + err.message + ", error code: " + err.code); 3880 }); 3881 ``` 3882 3883 3884## fs.createStream 3885 3886createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void 3887 3888基于文件路径创建文件流,使用callback异步回调。需要配合[Stream](#stream)中的close()函数关闭文件流。 3889 3890**系统能力**:SystemCapability.FileManagement.File.FileIO 3891 3892**参数:** 3893 3894| 参数名 | 类型 | 必填 | 说明 | 3895| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 3896| path | string | 是 | 文件的应用沙箱路径。 | 3897| mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 3898| callback | AsyncCallback<[Stream](#stream)> | 是 | 异步打开文件流之后的回调。 | 3899 3900**错误码:** 3901 3902接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3903 3904**示例:** 3905 3906 ```ts 3907 import { BusinessError } from '@kit.BasicServicesKit'; 3908 let filePath = pathDir + "/test.txt"; 3909 fs.createStream(filePath, "r+", (err: BusinessError, stream: fs.Stream) => { 3910 if (err) { 3911 console.error("create stream failed with error message: " + err.message + ", error code: " + err.code); 3912 } else { 3913 console.info("createStream succeed"); 3914 } 3915 stream.closeSync(); 3916 }) 3917 ``` 3918 3919## fs.createStreamSync 3920 3921createStreamSync(path: string, mode: string): Stream 3922 3923以同步方法基于文件路径创建文件流。需要配合[Stream](#stream)中的close()函数关闭文件流。 3924 3925**系统能力**:SystemCapability.FileManagement.File.FileIO 3926 3927**参数:** 3928 3929| 参数名 | 类型 | 必填 | 说明 | 3930| ------ | ------ | ---- | ------------------------------------------------------------ | 3931| path | string | 是 | 文件的应用沙箱路径。 | 3932| mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 3933 3934**返回值:** 3935 3936 | 类型 | 说明 | 3937 | ------------------ | --------- | 3938 | [Stream](#stream) | 返回文件流的结果。 | 3939 3940**错误码:** 3941 3942接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3943 3944**示例:** 3945 3946 ```ts 3947 let filePath = pathDir + "/test.txt"; 3948 let stream = fs.createStreamSync(filePath, "r+"); 3949 console.info("createStream succeed"); 3950 stream.closeSync(); 3951 ``` 3952 3953 3954## fs.fdopenStream 3955 3956fdopenStream(fd: number, mode: string): Promise<Stream> 3957 3958基于文件描述符打开文件流,使用Promise异步返回。需要配合[Stream](#stream)中的close()函数关闭文件流。 3959 3960**系统能力**:SystemCapability.FileManagement.File.FileIO 3961 3962**参数:** 3963 3964 | 参数名 | 类型 | 必填 | 说明 | 3965 | ---- | ------ | ---- | ---------------------------------------- | 3966 | fd | number | 是 | 已打开的文件描述符。 | 3967 | mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 3968 3969**返回值:** 3970 3971 | 类型 | 说明 | 3972 | --------------------------------- | --------- | 3973 | Promise<[Stream](#stream)> | Promise对象。返回文件流的结果。 | 3974 3975**错误码:** 3976 3977接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 3978 3979**示例:** 3980 3981 ```ts 3982 import { BusinessError } from '@kit.BasicServicesKit'; 3983 let filePath = pathDir + "/test.txt"; 3984 let file = fs.openSync(filePath); 3985 fs.fdopenStream(file.fd, "r+").then((stream: fs.Stream) => { 3986 console.info("openStream succeed"); 3987 stream.closeSync(); 3988 }).catch((err: BusinessError) => { 3989 console.error("openStream failed with error message: " + err.message + ", error code: " + err.code); 3990 // 文件流打开失败后,文件描述符需要手动关闭 3991 fs.closeSync(file); 3992 }); 3993 ``` 3994 3995> **注意:** 3996> 3997> 使用文件描述符创建的文件流,文件描述符的生命周期也交由文件流对象,在调用文件流的close()函数后,初始的文件描述符也会被关闭。 3998 3999## fs.fdopenStream 4000 4001fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void 4002 4003基于文件描述符打开文件流,使用callback异步回调。需要配合[Stream](#stream)中的close()函数关闭文件流。 4004 4005**系统能力**:SystemCapability.FileManagement.File.FileIO 4006 4007**参数:** 4008 4009 | 参数名 | 类型 | 必填 | 说明 | 4010 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 4011 | fd | number | 是 | 已打开的文件描述符。 | 4012 | mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 4013 | callback | AsyncCallback<[Stream](#stream)> | 是 | 异步打开文件流之后的回调。 | 4014 4015**错误码:** 4016 4017接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4018 4019**示例:** 4020 4021 ```ts 4022 import { BusinessError } from '@kit.BasicServicesKit'; 4023 let filePath = pathDir + "/test.txt"; 4024 let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); 4025 fs.fdopenStream(file.fd, "r+", (err: BusinessError, stream: fs.Stream) => { 4026 if (err) { 4027 console.error("fdopen stream failed with error message: " + err.message + ", error code: " + err.code); 4028 stream.closeSync(); 4029 } else { 4030 console.info("fdopen stream succeed"); 4031 // 文件流打开失败后,文件描述符需要手动关闭 4032 fs.closeSync(file); 4033 } 4034 }); 4035 ``` 4036 4037> **注意:** 4038> 4039> 使用文件描述符创建的文件流,文件描述符的生命周期也交由文件流对象,在调用文件流的close()函数后,初始的文件描述符也会被关闭。 4040 4041## fs.fdopenStreamSync 4042 4043fdopenStreamSync(fd: number, mode: string): Stream 4044 4045以同步方法基于文件描述符打开文件流。需要配合[Stream](#stream)中的close()函数关闭文件流。 4046 4047**系统能力**:SystemCapability.FileManagement.File.FileIO 4048 4049**参数:** 4050 4051 | 参数名 | 类型 | 必填 | 说明 | 4052 | ---- | ------ | ---- | ---------------------------------------- | 4053 | fd | number | 是 | 已打开的文件描述符。 | 4054 | mode | string | 是 | - r:打开只读文件,该文件必须存在。<br/>- r+:打开可读写的文件,该文件必须存在。<br/>- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | 4055 4056**返回值:** 4057 4058 | 类型 | 说明 | 4059 | ------------------ | --------- | 4060 | [Stream](#stream) | 返回文件流的结果。 | 4061 4062**错误码:** 4063 4064接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4065 4066**示例:** 4067 4068 ```ts 4069 let filePath = pathDir + "/test.txt"; 4070 let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE); 4071 let stream = fs.fdopenStreamSync(file.fd, "r+"); 4072 stream.closeSync(); 4073 ``` 4074 4075> **注意:** 4076> 4077> 使用文件描述符创建的文件流,文件描述符的生命周期也交由文件流对象,在调用文件流的close()函数后,初始的文件描述符也会被关闭。 4078 4079## fs.createReadStream<sup>12+</sup> 4080 4081createReadStream(path: string, options?: ReadStreamOptions ): ReadStream; 4082 4083以同步方法打开文件可读流。 4084 4085**系统能力**:SystemCapability.FileManagement.File.FileIO 4086 4087**参数:** 4088 4089 | 参数名 | 类型 | 必填 | 说明 | 4090 | ---- | ------ | ---- | ---------------------------------------- | 4091 | path | string | 是 | 文件路径。 | 4092 | options | [ReadStreamOptions](#readstreamoptions12) | 否 | 支持如下选项:<br/>- start,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- end,number类型,表示期望读取结束的位置。可选,默认文件末尾。 | 4093 4094**返回值:** 4095 4096 | 类型 | 说明 | 4097 | ------------------ | --------- | 4098 | [ReadStream](#readstream12) | 文件可读流。 | 4099 4100**错误码:** 4101 4102接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4103 4104**示例:** 4105 4106 ```ts 4107 // 创建文件可读流 4108 const rs = fs.createReadStream(`${pathDir}/read.txt`); 4109 // 创建文件可写流 4110 const ws = fs.createWriteStream(`${pathDir}/write.txt`); 4111 // 暂停模式拷贝文件 4112 rs.on('readable', () => { 4113 const data = rs.read(); 4114 if (!data) { 4115 return; 4116 } 4117 ws.write(data); 4118 }); 4119 ``` 4120 4121## fs.createWriteStream<sup>12+</sup> 4122 4123createWriteStream(path: string, options?: WriteStreamOptions): WriteStream; 4124 4125以同步方法打开文件可写流。 4126 4127**系统能力**:SystemCapability.FileManagement.File.FileIO 4128 4129**参数:** 4130 4131 | 参数名 | 类型 | 必填 | 说明 | 4132 | ---- | ------ | ---- | ---------------------------------------- | 4133 | path | string | 是 | 文件路径。 | 4134 | options | [WriteStreamOptions](#writestreamoptions12) | 否 | 支持如下选项:<br/>- start,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- mode,number 类型,创建文件可写流的[选项](#openmode),可选,默认以只写方式创建。 | 4135 4136**返回值:** 4137 4138 | 类型 | 说明 | 4139 | ------------------ | --------- | 4140 | [WriteStream](#writestream12) | 文件可写流。 | 4141 4142**错误码:** 4143 4144接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4145 4146**示例:** 4147 4148 ```ts 4149 // 创建文件可读流 4150 const rs = fs.createReadStream(`${pathDir}/read.txt`); 4151 // 创建文件可写流 4152 const ws = fs.createWriteStream(`${pathDir}/write.txt`); 4153 // 暂停模式拷贝文件 4154 rs.on('readable', () => { 4155 const data = rs.read(); 4156 if (!data) { 4157 return; 4158 } 4159 ws.write(data); 4160 }); 4161 ``` 4162 4163## AtomicFile<sup>15+</sup> 4164AtomicFile是一个用于对文件进行原子读写操作的类。 4165 4166在写操作时,通过写入临时文件,并在写入成功后将其重命名到原始文件位置来确保写入文件的完整性;而在写入失败时删除临时文件,不修改原始文件内容。 4167 4168使用者可以自行调用finishWrite或failWrite来完成文件内容的写入或回滚。 4169 4170**系统能力**:SystemCapability.FileManagement.File.FileIO 4171 4172### constructor<sup>15+</sup> 4173 4174constructor(path: string) 4175 4176对于给定路径的文件创建一个AtomicFile类。 4177 4178**系统能力**:SystemCapability.FileManagement.File.FileIO 4179 4180**参数:** 4181 4182 | 参数名 | 类型 | 必填 | 说明 | 4183 | ------ | ------ | ---- | -------------------------------------- | 4184 | path | string | 是 | 文件的沙箱路径。 | 4185 4186### getBaseFile<sup>15+</sup> 4187 4188getBaseFile(): File 4189 4190通过AtomicFile对象获取文件对象。 4191 4192文件fd由用户自己调用close关闭。 4193 4194**系统能力**:SystemCapability.FileManagement.File.FileIO 4195 4196**错误码:** 4197 4198接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件IO错误码)和[通用错误码](../errorcode-universal.md#通用错误码)。 4199 4200**示例:** 4201 4202```ts 4203import { hilog } from '@kit.PerformanceAnalysisKit'; 4204import { common } from '@kit.AbilityKit'; 4205import { fileIo as fs} from '@kit.CoreFileKit'; 4206 4207let context = getContext(this) as common.UIAbilityContext; 4208let pathDir = context.filesDir; 4209 4210try { 4211 let atomicFile = new fs.AtomicFile(`${pathDir}/write.txt`); 4212 let writeSream = atomicFile.startWrite(); 4213 writeSream.write("xxxxx","utf-8",()=> { 4214 atomicFile.finishWrite(); 4215 let File = atomicFile.getBaseFile(); 4216 hilog.info(0x0000, 'AtomicFile', 'getBaseFile File.fd is:%{public}d, path:%{public}s, name:%{public}s', File.fd, File.path, File.path); 4217 }) 4218} catch (err) { 4219 hilog.error(0x0000, 'AtomicFile', 'failed! err :%{public}s', err.message); 4220} 4221``` 4222 4223### openRead<sup>15+</sup> 4224 4225openRead(): ReadStream 4226 4227创建一个读文件流。 4228 4229**系统能力**:SystemCapability.FileManagement.File.FileIO 4230 4231**返回值:** 4232 4233 | 类型 | 说明 | 4234 | ------------------ | --------- | 4235 | [ReadStream](#readstream12) | 文件可读流。 | 4236 4237**错误码:** 4238 4239接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件IO错误码)和[通用错误码](../errorcode-universal.md#通用错误码)。 4240 4241**示例:** 4242 4243```ts 4244import { hilog } from '@kit.PerformanceAnalysisKit'; 4245import { common } from '@kit.AbilityKit'; 4246import { fileIo as fs} from '@kit.CoreFileKit'; 4247import { BusinessError } from '@kit.BasicServicesKit'; 4248 4249let context = getContext(this) as common.UIAbilityContext; 4250let pathDir = context.filesDir; 4251 4252try { 4253 let file = new fs.AtomicFile(`${pathDir}/read.txt`); 4254 let writeSream = file.startWrite(); 4255 writeSream.write("xxxxxx","utf-8",()=> { 4256 file.finishWrite(); 4257 setTimeout(()=>{ 4258 let readStream = file.openRead(); 4259 readStream.on('readable', () => { 4260 const data = readStream.read(); 4261 if (!data) { 4262 hilog.error(0x0000, 'AtomicFile', 'Read data is null'); 4263 return; 4264 } 4265 hilog.info(0x0000, 'AtomicFile', 'Read data is:%{public}s!', data); 4266 }); 4267 },1000); 4268 }) 4269} catch (err) { 4270 hilog.error(0x0000, 'AtomicFile', 'failed! , Cause: %{public}s', JSON.stringify(err) ?? ''); 4271} 4272``` 4273 4274### readFully<sup>15+</sup> 4275 4276readFully(): ArrayBuffer 4277 4278读取文件全部内容。 4279 4280**系统能力**:SystemCapability.FileManagement.File.FileIO 4281 4282**返回值:** 4283 4284 | 类型 | 说明 | 4285 | ------------------ | --------- | 4286 | ArrayBuffer | 文件的全部内容。 | 4287 4288**错误码:** 4289 4290接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件IO错误码)和[通用错误码](../errorcode-universal.md#通用错误码)。 4291 4292**示例:** 4293 4294```ts 4295import { hilog } from '@kit.PerformanceAnalysisKit'; 4296import { common } from '@kit.AbilityKit'; 4297import { fileIo as fs} from '@kit.CoreFileKit'; 4298import { util, buffer } from '@kit.ArkTS'; 4299import { BusinessError } from '@kit.BasicServicesKit'; 4300 4301let context = getContext(this) as common.UIAbilityContext; 4302let pathDir = context.filesDir; 4303 4304try { 4305 let file = new fs.AtomicFile(`${pathDir}/read.txt`); 4306 let writeSream = file.startWrite(); 4307 writeSream.write("xxxxxxxxxxx","utf-8",()=> { 4308 file.finishWrite(); 4309 setTimeout(()=>{ 4310 let data = file.readFully(); 4311 let decoder = util.TextDecoder.create('utf-8'); 4312 let str = decoder.decodeToString(new Uint8Array(data)); 4313 hilog.info(0x0000, 'AtomicFile', 'readFully str is :%{public}s!', str); 4314 },1000); 4315 }) 4316} catch (err) { 4317 hilog.error(0x0000, 'AtomicFile', 'failed!, Cause: %{public}s', JSON.stringify(err) ?? ''); 4318} 4319``` 4320 4321### startWrite<sup>15+</sup> 4322 4323startWrite(): WriteStream 4324 4325对文件开始新的写入操作。将返回一个WriteStream,用于在其中写入新的文件数据。 4326 4327当文件不存在时新建文件。 4328 4329在写入文件完成后,写入成功需要调用finishWrite(),写入失败需要调用failWrite()。 4330 4331**系统能力**:SystemCapability.FileManagement.File.FileIO 4332 4333**返回值:** 4334 4335 | 类型 | 说明 | 4336 | ------------------ | --------- | 4337 | [WriteStream](#writestream12) | 文件可写流。 | 4338 4339**错误码:** 4340 4341接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件IO错误码)和[通用错误码](../errorcode-universal.md#通用错误码)。 4342 4343**示例:** 4344 4345```ts 4346import { hilog } from '@kit.PerformanceAnalysisKit'; 4347import { common } from '@kit.AbilityKit'; 4348import { fileIo as fs} from '@kit.CoreFileKit'; 4349 4350let context = getContext(this) as common.UIAbilityContext; 4351let pathDir = context.filesDir; 4352 4353try { 4354 let file = new fs.AtomicFile(`${pathDir}/write.txt`); 4355 let writeSream = file.startWrite(); 4356 hilog.error(0x0000, 'AtomicFile', 'startWrite end'); 4357 writeSream.write("xxxxxxxx","utf-8",()=> { 4358 hilog.info(0x0000, 'AtomicFile', 'write end'); 4359 }) 4360} catch (err) { 4361 hilog.error(0x0000, 'AtomicFile', 'failed! err :%{public}s', err.message); 4362} 4363``` 4364 4365### finishWrite<sup>15+</sup> 4366 4367finishWrite(): void 4368 4369在完成对startWrite返回流的写入操作时调用,表示文件写入成功。 4370 4371**系统能力**:SystemCapability.FileManagement.File.FileIO 4372 4373**错误码:** 4374 4375接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件IO错误码)和[通用错误码](../errorcode-universal.md#通用错误码)。 4376 4377**示例:** 4378 4379```ts 4380import { hilog } from '@kit.PerformanceAnalysisKit'; 4381import { common } from '@kit.AbilityKit'; 4382import { fileIo as fs} from '@kit.CoreFileKit'; 4383 4384let context = getContext(this) as common.UIAbilityContext; 4385let pathDir = context.filesDir; 4386 4387try { 4388 let file = new fs.AtomicFile(`${pathDir}/write.txt`); 4389 let writeSream = file.startWrite(); 4390 writeSream.write("xxxxxxxxxxx","utf-8",()=> { 4391 file.finishWrite(); 4392 }) 4393} catch (err) { 4394 hilog.error(0x0000, 'AtomicFile', 'failed! , Cause: %{public}s', JSON.stringify(err) ?? ''); 4395} 4396``` 4397 4398### failWrite<sup>15+</sup> 4399 4400failWrite(): void 4401 4402文件写入失败后调用,将执行文件回滚操作。 4403 4404**系统能力**:SystemCapability.FileManagement.File.FileIO 4405 4406**错误码:** 4407 4408接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件IO错误码)和[通用错误码](../errorcode-universal.md#通用错误码)。 4409 4410**示例:** 4411 4412```ts 4413import { hilog } from '@kit.PerformanceAnalysisKit'; 4414import { common } from '@kit.AbilityKit'; 4415import { fileIo as fs} from '@kit.CoreFileKit'; 4416import { util, buffer } from '@kit.ArkTS'; 4417import { BusinessError } from '@kit.BasicServicesKit'; 4418 4419let context = getContext(this) as common.UIAbilityContext; 4420let pathDir = context.filesDir; 4421 4422let file = new fs.AtomicFile(`${pathDir}/write.txt`); 4423try { 4424 let writeSream = file.startWrite(); 4425 writeSream.write("xxxxxxxxxxx","utf-8",()=> { 4426 hilog.info(0x0000, 'AtomicFile', 'write succeed!'); 4427 }) 4428} catch (err) { 4429 file.failWrite(); 4430 hilog.error(0x0000, 'AtomicFile', 'failed! , Cause: %{public}s', JSON.stringify(err) ?? ''); 4431} 4432``` 4433 4434### delete<sup>15+</sup> 4435 4436delete(): void 4437 4438删除AtomicFile类,会删除原始文件和临时文件。 4439 4440**系统能力**:SystemCapability.FileManagement.File.FileIO 4441 4442**错误码:** 4443 4444接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件IO错误码)和[通用错误码](../errorcode-universal.md#通用错误码)。 4445 4446**示例:** 4447 4448```ts 4449import { common } from '@kit.AbilityKit'; 4450import { fileIo as fs} from '@kit.CoreFileKit'; 4451 4452let context = getContext(this) as common.UIAbilityContext; 4453let pathDir = context.filesDir; 4454 4455try { 4456 let file = new fs.AtomicFile(`${pathDir}/read.txt`); 4457 let writeSream = file.startWrite(); 4458 writeSream.write("xxxxxxxxxxx","utf-8",()=> { 4459 file.finishWrite(); 4460 setTimeout(()=>{ 4461 let data = file.readFully(); 4462 let decoder = util.TextDecoder.create('utf-8'); 4463 let str = decoder.decodeToString(new Uint8Array(data)); 4464 hilog.info(0x0000, 'AtomicFile', 'readFully str is :%{public}s!', str); 4465 file.delete(); 4466 },1000); 4467 }) 4468} catch (err) { 4469 hilog.error(0x0000, 'AtomicFile', 'failed!, Cause: %{public}s', JSON.stringify(err) ?? ''); 4470} 4471``` 4472 4473## fs.createWatcher<sup>10+</sup> 4474 4475createWatcher(path: string, events: number, listener: WatchEventListener): Watcher 4476 4477创建Watcher对象,用来监听文件或目录变动。 4478 4479**系统能力**:SystemCapability.FileManagement.File.FileIO 4480 4481**参数:** 4482 4483 | 参数名 | 类型 | 必填 | 说明 | 4484 | ---- | ------ | ---- | ---------------------------------------- | 4485 | path | string | 是 | 监听文件或目录的沙箱路径。 | 4486 | events | number | 是 | 监听变动的事件集,多个事件通过或(\|)的方式进行集合。<br/>- 0x1: IN_ACCESS, 文件被访问。<br/>- 0x2: IN_MODIFY,文件内容被修改。<br/>- 0x4: IN_ATTRIB,文件元数据被修改。<br/>- 0x8: IN_CLOSE_WRITE,文件在打开时进行了写操作,然后被关闭。<br/>- 0x10: IN_CLOSE_NOWRITE,文件或目录在打开时未进行写操作,然后被关闭。<br/>- 0x20: IN_OPEN,文件或目录被打开。 <br/>- 0x40: IN_MOVED_FROM,监听目录中文件被移动走。<br/>- 0x80: IN_MOVED_TO,监听目录中文件被移动过来。<br/>- 0x100: IN_CREATE,监听目录中文件或子目录被创建。<br/>- 0x200: IN_DELETE,监听目录中文件或子目录被删除。<br/>- 0x400: IN_DELETE_SELF,监听的目录被删除,删除后监听停止。<br/>- 0x800: IN_MOVE_SELF,监听的文件或目录被移动,移动后监听继续。<br/>- 0xfff: IN_ALL_EVENTS,监听以上所有事件。| 4487 | listener | [WatchEventListener](#watcheventlistener10) | 是 | 监听事件发生后的回调。监听事件每发生一次,回调一次。 | 4488 4489**返回值:** 4490 4491 | 类型 | 说明 | 4492 | ------------------ | --------- | 4493 | [Watcher](#watcher10) | 返回Watcher对象。 | 4494 4495**错误码:** 4496 4497接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4498 4499**示例:** 4500 4501 ```ts 4502 import { fileIo as fs, WatchEvent } from '@kit.CoreFileKit'; 4503 let filePath = pathDir + "/test.txt"; 4504 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 4505 let watcher = fs.createWatcher(filePath, 0x2 | 0x10, (watchEvent: WatchEvent) => { 4506 if (watchEvent.event == 0x2) { 4507 console.info(watchEvent.fileName + 'was modified'); 4508 } else if (watchEvent.event == 0x10) { 4509 console.info(watchEvent.fileName + 'was closed'); 4510 } 4511 }); 4512 watcher.start(); 4513 fs.writeSync(file.fd, 'test'); 4514 fs.closeSync(file); 4515 watcher.stop(); 4516 ``` 4517 4518## WatchEventListener<sup>10+</sup> 4519 4520(event: WatchEvent): void 4521 4522事件监听类。 4523 4524**系统能力**:SystemCapability.FileManagement.File.FileIO 4525 4526**参数:** 4527 4528 | 参数名 | 类型 | 必填 | 说明 | 4529 | ---- | ------ | ---- | ---------------------------------------- | 4530 | event | [WatchEvent](#watchevent10) | 是 | 回调的事件类。 | 4531 4532## WatchEvent<sup>10+</sup> 4533 4534事件类 4535 4536**系统能力**:SystemCapability.FileManagement.File.FileIO 4537 4538### 属性 4539 4540| 名称 | 类型 | 只读 | 可写 | 说明 | 4541| ---- | ------ | ---- | ---- | ------- | 4542| fileName | string | 是 | 否 | 发生监听事件对应文件的沙箱路径,该沙箱路径包含文件名称。 | 4543| event | number | 是 | 否 | 监听变动的事件集,多个事件通过或(\|)的方式进行集合。<br/>- 0x1: IN_ACCESS, 文件被访问。<br/>- 0x2: IN_MODIFY,文件内容被修改。<br/>- 0x4: IN_ATTRIB,文件元数据被修改。<br/>- 0x8: IN_CLOSE_WRITE,文件在打开时进行了写操作,然后被关闭。<br/>- 0x10: IN_CLOSE_NOWRITE,文件或目录在打开时未进行写操作,然后被关闭。<br/>- 0x20: IN_OPEN,文件或目录被打开。 <br/>- 0x40: IN_MOVED_FROM,监听目录中文件被移动走。<br/>- 0x80: IN_MOVED_TO,监听目录中文件被移动过来。<br/>- 0x100: IN_CREATE,监听目录中文件或子目录被创建。<br/>- 0x200: IN_DELETE,监听目录中文件或子目录被删除。<br/>- 0x400: IN_DELETE_SELF,监听的目录被删除,删除后监听停止。<br/>- 0x800: IN_MOVE_SELF,监听的文件或目录被移动,移动后监听继续。<br/>- 0xfff: IN_ALL_EVENTS,监听以上所有事件。 | 4544| cookie | number | 是 | 否 | 绑定相关事件的cookie。当前仅支持事件IN_MOVED_FROM与IN_MOVED_TO,同一个文件的移动事件IN_MOVED_FROM和IN_MOVED_TO具有相同的cookie值。 | 4545 4546## Progress<sup>11+</sup> 4547 4548拷贝进度回调数据 4549 4550**系统能力**:SystemCapability.FileManagement.File.FileIO 4551 4552| 名称 | 类型 | 只读 | 可写 | 说明 | 4553| ---- | ------ | ---- | ---- | ------- | 4554| processedSize | number | 是 | 否 | 已拷贝的数据大小。 | 4555| totalSize | number | 是 | 否 | 待拷贝的数据总大小。 | 4556 4557## TaskSignal<sup>12+</sup> 4558 4559拷贝中断信号。 4560 4561**系统能力**:SystemCapability.FileManagement.File.FileIO 4562 4563### cancel<sup>12+</sup> 4564 4565cancel(): void 4566 4567取消拷贝任务。 4568 4569**系统能力**:SystemCapability.FileManagement.File.FileIO 4570 4571**错误码:** 4572 4573接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4574 4575**示例:** 4576 4577```ts 4578import { BusinessError } from '@kit.BasicServicesKit'; 4579import { fileIo as fs } from '@kit.CoreFileKit'; 4580import { fileUri } from '@kit.CoreFileKit'; 4581import common from '@ohos.app.ability.common'; 4582let context = getContext(this) as common.UIAbilityContext; 4583let pathDir: string = context.filesDir; 4584let srcDirPathLocal: string = pathDir + "/src"; 4585let dstDirPathLocal: string = pathDir + "/dest"; 4586let srcDirUriLocal: string = fileUri.getUriFromPath(srcDirPathLocal); 4587let dstDirUriLocal: string = fileUri.getUriFromPath(dstDirPathLocal); 4588let copySignal = new fs.TaskSignal; 4589let progressListener: fs.ProgressListener = (progress: fs.Progress) => { 4590 console.info(`progressSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`); 4591 if (progress.processedSize / progress.totalSize > 0.5) { 4592 copySignal.cancel(); 4593 } 4594}; 4595let options: fs.CopyOptions = { 4596 "progressListener" : progressListener, 4597 "copySignal" : new fs.TaskSignal, 4598} 4599console.info("copyFileWithCancel success."); 4600try { 4601 fs.copy(srcDirPathLocal, dstDirUriLocal, options, (err: BusinessError) => { 4602 if (err) { 4603 console.info("copyFileWithCancel fail."); 4604 return; 4605 } 4606 console.info("copyFileWithCancel success."); 4607 }) 4608} catch (err) { 4609 console.error("copyFileWithCancel failed with invalid param."); 4610} 4611 4612``` 4613 4614### onCancel<sup>12+</sup> 4615 4616onCancel(): Promise<string> 4617 4618取消拷贝事件监听。 4619 4620**系统能力**:SystemCapability.FileManagement.File.FileIO 4621 4622**返回值:** 4623 4624 | 类型 | 说明 | 4625 | --------------------- | ---------- | 4626 | Promise<string> | Promise对象。最后一个拷贝的文件路径。 | 4627 4628**错误码:** 4629 4630接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4631 4632**示例:** 4633 4634```ts 4635import { fileIo as fs } from '@kit.CoreFileKit'; 4636import { TaskSignal } from '@ohos.file.fs'; 4637let copySignal: fs.TaskSignal = new TaskSignal(); 4638copySignal.onCancel().then(() => { 4639 console.info("copyFileWithCancel success."); 4640}); 4641``` 4642 4643## CopyOptions<sup>11+</sup> 4644 4645拷贝进度回调监听 4646 4647**系统能力**:SystemCapability.FileManagement.File.FileIO 4648 4649| 名称 | 类型 | 可读 | 可写 | 说明 | 4650| ---- | ------ | ---- | ---- | ------- | 4651| progressListener | [ProgressListener](#progresslistener11) | 是 | 是 | 拷贝进度监听。 | 4652| copySignal | [TaskSignal](#tasksignal12) | 是 | 是 | 取消拷贝信号。 | 4653 4654## ProgressListener<sup>11+</sup> 4655 4656拷贝进度监听。 4657 4658**系统能力**:SystemCapability.FileManagement.File.FileIO 4659 4660| 类型 | 说明 | 4661| ----| ------| 4662|(progress: [Progress](#progress11)) => void| 拷贝进度监听| 4663 4664**示例:** 4665 4666 ```ts 4667 import { TaskSignal } from '@kit.CoreFileKit'; 4668 let copySignal: fs.TaskSignal = new TaskSignal(); 4669 let progressListener: fs.ProgressListener = (progress: fs.Progress) => { 4670 console.info(`processedSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`); 4671 }; 4672 let copyOption: fs.CopyOptions = { 4673 "progressListener" : progressListener, 4674 "copySignal" : copySignal, 4675 } 4676 ``` 4677 4678## Stat 4679 4680文件具体信息,在调用Stat的方法前,需要先通过[stat()](#fsstat)方法(同步或异步)来构建一个Stat实例。 4681 4682**系统能力**:SystemCapability.FileManagement.File.FileIO 4683 4684### 属性 4685 4686| 名称 | 类型 | 只读 | 可写 | 说明 | 4687| ------ | ------ | ---- | ---- | ---------------------------------------- | 4688| ino | bigint | 是 | 否 | 标识该文件。通常同设备上的不同文件的INO不同。| | 4689| mode | number | 是 | 否 | 表示文件权限,各特征位的含义如下:<br/>**说明:** 以下值为八进制,取得的返回值为十进制,请换算后查看。<br/>- 0o400:用户读,对于普通文件,所有者可读取文件;对于目录,所有者可读取目录项。<br/>- 0o200:用户写,对于普通文件,所有者可写入文件;对于目录,所有者可创建/删除目录项。<br/>- 0o100:用户执行,对于普通文件,所有者可执行文件;对于目录,所有者可在目录中搜索给定路径名。<br/>- 0o040:用户组读,对于普通文件,所有用户组可读取文件;对于目录,所有用户组可读取目录项。<br/>- 0o020:用户组写,对于普通文件,所有用户组可写入文件;对于目录,所有用户组可创建/删除目录项。<br/>- 0o010:用户组执行,对于普通文件,所有用户组可执行文件;对于目录,所有用户组是否可在目录中搜索给定路径名。<br/>- 0o004:其他读,对于普通文件,其余用户可读取文件;对于目录,其他用户组可读取目录项。<br/>- 0o002:其他写,对于普通文件,其余用户可写入文件;对于目录,其他用户组可创建/删除目录项。<br/>- 0o001:其他执行,对于普通文件,其余用户可执行文件;对于目录,其他用户组可在目录中搜索给定路径名。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 4690| uid | number | 是 | 否 | 文件所有者的ID。| 4691| gid | number | 是 | 否 | 文件所有组的ID。| 4692| size | number | 是 | 否 | 文件的大小,以字节为单位。仅对普通文件有效。 <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 4693| atime | number | 是 | 否 | 上次访问该文件的时间,表示距1970年1月1日0时0分0秒的秒数。 <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 4694| mtime | number | 是 | 否 | 上次修改该文件的时间,表示距1970年1月1日0时0分0秒的秒数。 <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 4695| ctime | number | 是 | 否 | 最近改变文件状态的时间,表示距1970年1月1日0时0分0秒的秒数。 | 4696| atimeNs<sup>15+</sup> | bigint | 是 | 否 | 上次访问该文件的时间,表示距1970年1月1日0时0分0秒的纳秒数。 | 4697| mtimeNs<sup>15+</sup> | bigint | 是 | 否 | 上次修改该文件的时间,表示距1970年1月1日0时0分0秒的纳秒数。 | 4698| ctimeNs<sup>15+</sup> | bigint | 是 | 否 | 最近改变文件状态的时间,表示距1970年1月1日0时0分0秒的纳秒数。 | 4699| location<sup>11+</sup> | [LocaltionType](#locationtype11)| 是 |否| 文件的位置,表示该文件是本地文件或者云端文件。 4700 4701### isBlockDevice 4702 4703isBlockDevice(): boolean 4704 4705用于判断文件是否是块特殊文件。一个块特殊文件只能以块为粒度进行访问,且访问的时候带缓存。 4706 4707**系统能力**:SystemCapability.FileManagement.File.FileIO 4708 4709**返回值:** 4710 4711 | 类型 | 说明 | 4712 | ------- | ---------------- | 4713 | boolean | 表示文件是否是块特殊设备。 | 4714 4715**错误码:** 4716 4717接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4718 4719**示例:** 4720 4721 ```ts 4722 let filePath = pathDir + "/test.txt"; 4723 let isBLockDevice = fs.statSync(filePath).isBlockDevice(); 4724 ``` 4725 4726### isCharacterDevice 4727 4728isCharacterDevice(): boolean 4729 4730用于判断文件是否是字符特殊文件。一个字符特殊设备可进行随机访问,且访问的时候不带缓存。 4731 4732**系统能力**:SystemCapability.FileManagement.File.FileIO 4733 4734**返回值:** 4735 4736 | 类型 | 说明 | 4737 | ------- | ----------------- | 4738 | boolean | 表示文件是否是字符特殊设备。 | 4739 4740**错误码:** 4741 4742接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4743 4744**示例:** 4745 4746 ```ts 4747 let filePath = pathDir + "/test.txt"; 4748 let isCharacterDevice = fs.statSync(filePath).isCharacterDevice(); 4749 ``` 4750 4751### isDirectory 4752 4753isDirectory(): boolean 4754 4755用于判断文件是否是目录。 4756 4757**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 4758 4759**系统能力**:SystemCapability.FileManagement.File.FileIO 4760 4761**返回值:** 4762 4763 | 类型 | 说明 | 4764 | ------- | ------------- | 4765 | boolean | 表示文件是否是目录。 | 4766 4767**错误码:** 4768 4769接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4770 4771**示例:** 4772 4773 ```ts 4774 let dirPath = pathDir + "/test"; 4775 let isDirectory = fs.statSync(dirPath).isDirectory(); 4776 ``` 4777 4778### isFIFO 4779 4780isFIFO(): boolean 4781 4782用于判断文件是否是命名管道(有时也称为FIFO)。命名管道通常用于进程间通信。 4783 4784**系统能力**:SystemCapability.FileManagement.File.FileIO 4785 4786**返回值:** 4787 4788 | 类型 | 说明 | 4789 | ------- | --------------------- | 4790 | boolean | 表示文件是否是 FIFO。 | 4791 4792**错误码:** 4793 4794接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4795 4796**示例:** 4797 4798 ```ts 4799 let filePath = pathDir + "/test.txt"; 4800 let isFIFO = fs.statSync(filePath).isFIFO(); 4801 ``` 4802 4803### isFile 4804 4805isFile(): boolean 4806 4807用于判断文件是否是普通文件。 4808 4809**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 4810 4811**系统能力**:SystemCapability.FileManagement.File.FileIO 4812 4813**返回值:** 4814 4815 | 类型 | 说明 | 4816 | ------- | --------------- | 4817 | boolean | 表示文件是否是普通文件。 | 4818 4819**错误码:** 4820 4821接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4822 4823**示例:** 4824 4825 ```ts 4826 let filePath = pathDir + "/test.txt"; 4827 let isFile = fs.statSync(filePath).isFile(); 4828 ``` 4829 4830### isSocket 4831 4832isSocket(): boolean 4833 4834用于判断文件是否是套接字。 4835 4836**系统能力**:SystemCapability.FileManagement.File.FileIO 4837 4838**返回值:** 4839 4840 | 类型 | 说明 | 4841 | ------- | -------------- | 4842 | boolean | 表示文件是否是套接字。 | 4843 4844**错误码:** 4845 4846接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4847 4848**示例:** 4849 4850 ```ts 4851 let filePath = pathDir + "/test.txt"; 4852 let isSocket = fs.statSync(filePath).isSocket(); 4853 ``` 4854 4855### isSymbolicLink 4856 4857isSymbolicLink(): boolean 4858 4859用于判断文件是否是符号链接。 4860 4861**系统能力**:SystemCapability.FileManagement.File.FileIO 4862 4863**返回值:** 4864 4865 | 类型 | 说明 | 4866 | ------- | --------------- | 4867 | boolean | 表示文件是否是符号链接。 | 4868 4869**错误码:** 4870 4871接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4872 4873**示例:** 4874 4875 ```ts 4876 let filePath = pathDir + "/test"; 4877 let isSymbolicLink = fs.statSync(filePath).isSymbolicLink(); 4878 ``` 4879 4880## Stream 4881 4882文件流,在调用Stream的方法前,需要先通过[fs.createStream](#fscreatestream)方法或者[fs.fdopenStream](#fsfdopenstream)(同步或异步)来构建一个Stream实例。 4883 4884### close 4885 4886close(): Promise<void> 4887 4888关闭文件流,使用Promise异步返回。 4889 4890**系统能力**:SystemCapability.FileManagement.File.FileIO 4891 4892**返回值:** 4893 4894 | 类型 | 说明 | 4895 | ------------------- | ------------- | 4896 | Promise<void> | Promise对象。无返回值。 | 4897 4898**错误码:** 4899 4900接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4901 4902**示例:** 4903 4904 ```ts 4905 import { BusinessError } from '@kit.BasicServicesKit'; 4906 let filePath = pathDir + "/test.txt"; 4907 let stream = fs.createStreamSync(filePath, "r+"); 4908 stream.close().then(() => { 4909 console.info("close fileStream succeed"); 4910 }).catch((err: BusinessError) => { 4911 console.error("close fileStream failed with error message: " + err.message + ", error code: " + err.code); 4912 }); 4913 ``` 4914 4915### close 4916 4917close(callback: AsyncCallback<void>): void 4918 4919异步关闭文件流,使用callback异步回调。 4920 4921**系统能力**:SystemCapability.FileManagement.File.FileIO 4922 4923**参数:** 4924 4925 | 参数名 | 类型 | 必填 | 说明 | 4926 | -------- | ------------------------- | ---- | ------------- | 4927 | callback | AsyncCallback<void> | 是 | 异步关闭文件流之后的回调。 | 4928 4929**错误码:** 4930 4931接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4932 4933**示例:** 4934 4935 ```ts 4936 import { BusinessError } from '@kit.BasicServicesKit'; 4937 let filePath = pathDir + "/test.txt"; 4938 let stream = fs.createStreamSync(filePath, "r+"); 4939 stream.close((err: BusinessError) => { 4940 if (err) { 4941 console.error("close stream failed with error message: " + err.message + ", error code: " + err.code); 4942 } else { 4943 console.info("close stream succeed"); 4944 } 4945 }); 4946 ``` 4947 4948### closeSync 4949 4950closeSync(): void 4951 4952同步关闭文件流。 4953 4954**系统能力**:SystemCapability.FileManagement.File.FileIO 4955 4956**错误码:** 4957 4958接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4959 4960**示例:** 4961 4962 ```ts 4963 let filePath = pathDir + "/test.txt"; 4964 let stream = fs.createStreamSync(filePath, "r+"); 4965 stream.closeSync(); 4966 ``` 4967 4968### flush 4969 4970flush(): Promise<void> 4971 4972刷新文件流,使用Promise异步返回。 4973 4974**系统能力**:SystemCapability.FileManagement.File.FileIO 4975 4976**返回值:** 4977 4978 | 类型 | 说明 | 4979 | ------------------- | ------------- | 4980 | Promise<void> | Promise对象。返回表示异步刷新文件流的结果。 | 4981 4982**错误码:** 4983 4984接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 4985 4986**示例:** 4987 4988 ```ts 4989 import { BusinessError } from '@kit.BasicServicesKit'; 4990 let filePath = pathDir + "/test.txt"; 4991 let stream = fs.createStreamSync(filePath, "r+"); 4992 stream.flush().then(() => { 4993 console.info("flush succeed"); 4994 stream.close(); 4995 }).catch((err: BusinessError) => { 4996 console.error("flush failed with error message: " + err.message + ", error code: " + err.code); 4997 }); 4998 ``` 4999 5000### flush 5001 5002flush(callback: AsyncCallback<void>): void 5003 5004异步刷新文件流,使用callback异步回调。 5005 5006**系统能力**:SystemCapability.FileManagement.File.FileIO 5007 5008**参数:** 5009 5010 | 参数名 | 类型 | 必填 | 说明 | 5011 | -------- | ------------------------- | ---- | -------------- | 5012 | callback | AsyncCallback<void> | 是 | 异步刷新文件流后的回调函数。 | 5013 5014**错误码:** 5015 5016接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5017 5018**示例:** 5019 5020 ```ts 5021 import { BusinessError } from '@kit.BasicServicesKit'; 5022 let filePath = pathDir + "/test.txt"; 5023 let stream = fs.createStreamSync(filePath, "r+"); 5024 stream.flush((err: BusinessError) => { 5025 if (err) { 5026 console.error("flush stream failed with error message: " + err.message + ", error code: " + err.code); 5027 } else { 5028 console.info("flush succeed"); 5029 stream.close(); 5030 } 5031 }); 5032 ``` 5033 5034### flushSync 5035 5036flushSync(): void 5037 5038同步刷新文件流。 5039 5040**系统能力**:SystemCapability.FileManagement.File.FileIO 5041 5042**错误码:** 5043 5044接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5045 5046**示例:** 5047 5048 ```ts 5049 let filePath = pathDir + "/test.txt"; 5050 let stream = fs.createStreamSync(filePath, "r+"); 5051 stream.flushSync(); 5052 stream.close(); 5053 ``` 5054 5055### write 5056 5057write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise<number> 5058 5059将数据写入流文件,使用Promise异步返回。 5060 5061**系统能力**:SystemCapability.FileManagement.File.FileIO 5062 5063**参数:** 5064 5065 | 参数名 | 类型 | 必填 | 说明 | 5066 | ------- | ------------------------------- | ---- | ---------------------------------------- | 5067 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5068 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5069 5070**返回值:** 5071 5072 | 类型 | 说明 | 5073 | --------------------- | -------- | 5074 | Promise<number> | Promise对象。返回实际写入的长度。 | 5075 5076**错误码:** 5077 5078接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5079 5080**示例:** 5081 5082 ```ts 5083 import { BusinessError } from '@kit.BasicServicesKit'; 5084 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5085 let filePath = pathDir + "/test.txt"; 5086 let stream = fs.createStreamSync(filePath, "r+"); 5087 let writeOption: WriteOptions = { 5088 offset: 5, 5089 length: 5, 5090 encoding: 'utf-8' 5091 }; 5092 stream.write("hello, world", writeOption).then((number: number) => { 5093 console.info("write succeed and size is:" + number); 5094 stream.close(); 5095 }).catch((err: BusinessError) => { 5096 console.error("write failed with error message: " + err.message + ", error code: " + err.code); 5097 }); 5098 ``` 5099 5100### write 5101 5102write(buffer: ArrayBuffer | string, options?: WriteOptions, callback: AsyncCallback<number>): void 5103 5104将数据写入流文件,使用callback异步回调。 5105 5106**系统能力**:SystemCapability.FileManagement.File.FileIO 5107 5108**参数:** 5109 5110 | 参数名 | 类型 | 必填 | 说明 | 5111 | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 5112 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5113 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5114 | callback | AsyncCallback<number> | 是 | 异步写入完成后执行的回调函数。 | 5115 5116**错误码:** 5117 5118接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5119 5120**示例:** 5121 5122 ```ts 5123 import { BusinessError } from '@kit.BasicServicesKit'; 5124 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5125 let filePath = pathDir + "/test.txt"; 5126 let stream = fs.createStreamSync(filePath, "r+"); 5127 let writeOption: WriteOptions = { 5128 offset: 5, 5129 length: 5, 5130 encoding: 'utf-8' 5131 }; 5132 stream.write("hello, world", writeOption, (err: BusinessError, bytesWritten: number) => { 5133 if (err) { 5134 console.error("write stream failed with error message: " + err.message + ", error code: " + err.code); 5135 } else { 5136 if (bytesWritten) { 5137 console.info("write succeed and size is:" + bytesWritten); 5138 stream.close(); 5139 } 5140 } 5141 }); 5142 ``` 5143 5144### writeSync 5145 5146writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number 5147 5148以同步方法将数据写入流文件。 5149 5150**系统能力**:SystemCapability.FileManagement.File.FileIO 5151 5152**参数:** 5153 5154 | 参数名 | 类型 | 必填 | 说明 | 5155 | ------- | ------------------------------- | ---- | ---------------------------------------- | 5156 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5157 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5158 5159**返回值:** 5160 5161 | 类型 | 说明 | 5162 | ------ | -------- | 5163 | number | 实际写入的长度。 | 5164 5165**错误码:** 5166 5167接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5168 5169**示例:** 5170 5171 ```ts 5172 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5173 let filePath = pathDir + "/test.txt"; 5174 let stream = fs.createStreamSync(filePath,"r+"); 5175 let writeOption: WriteOptions = { 5176 offset: 5, 5177 length: 5, 5178 encoding: 'utf-8' 5179 }; 5180 let num = stream.writeSync("hello, world", writeOption); 5181 stream.close(); 5182 ``` 5183 5184### read 5185 5186read(buffer: ArrayBuffer, options?: ReadOptions): Promise<number> 5187 5188从流文件读取数据,使用Promise异步返回。 5189 5190**系统能力**:SystemCapability.FileManagement.File.FileIO 5191 5192**参数:** 5193 5194 | 参数名 | 类型 | 必填 | 说明 | 5195 | ------- | ----------- | ---- | ---------------------------------------- | 5196 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5197 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。 | 5198 5199**返回值:** 5200 5201 | 类型 | 说明 | 5202 | ---------------------------------- | ------ | 5203 | Promise<number> | Promise对象。返回读取的结果。 | 5204 5205**错误码:** 5206 5207接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5208 5209**示例:** 5210 5211 ```ts 5212 import { BusinessError } from '@kit.BasicServicesKit'; 5213 import { buffer } from '@kit.ArkTS'; 5214 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5215 let filePath = pathDir + "/test.txt"; 5216 let stream = fs.createStreamSync(filePath, "r+"); 5217 let arrayBuffer = new ArrayBuffer(4096); 5218 let readOption: ReadOptions = { 5219 offset: 5, 5220 length: 5 5221 }; 5222 stream.read(arrayBuffer, readOption).then((readLen: number) => { 5223 console.info("read data succeed"); 5224 let buf = buffer.from(arrayBuffer, 0, readLen); 5225 console.log(`The content of file: ${buf.toString()}`); 5226 stream.close(); 5227 }).catch((err: BusinessError) => { 5228 console.error("read data failed with error message: " + err.message + ", error code: " + err.code); 5229 }); 5230 ``` 5231 5232### read 5233 5234read(buffer: ArrayBuffer, options?: ReadOptions, callback: AsyncCallback<number>): void 5235 5236从流文件读取数据,使用callback异步回调。 5237 5238**系统能力**:SystemCapability.FileManagement.File.FileIO 5239 5240**参数:** 5241 5242 | 参数名 | 类型 | 必填 | 说明 | 5243 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 5244 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5245 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读. | 5246 | callback | AsyncCallback<number> | 是 | 异步从流文件读取数据之后的回调。 | 5247 5248**错误码:** 5249 5250接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5251 5252**示例:** 5253 5254 ```ts 5255 import { BusinessError } from '@kit.BasicServicesKit'; 5256 import { buffer } from '@kit.ArkTS'; 5257 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5258 let filePath = pathDir + "/test.txt"; 5259 let stream = fs.createStreamSync(filePath, "r+"); 5260 let arrayBuffer = new ArrayBuffer(4096); 5261 let readOption: ReadOptions = { 5262 offset: 5, 5263 length: 5 5264 }; 5265 stream.read(arrayBuffer, readOption, (err: BusinessError, readLen: number) => { 5266 if (err) { 5267 console.error("read stream failed with error message: " + err.message + ", error code: " + err.code); 5268 } else { 5269 console.info("read data succeed"); 5270 let buf = buffer.from(arrayBuffer, 0, readLen); 5271 console.log(`The content of file: ${buf.toString()}`); 5272 stream.close(); 5273 } 5274 }); 5275 ``` 5276 5277### readSync 5278 5279readSync(buffer: ArrayBuffer, options?: ReadOptions): number 5280 5281以同步方法从流文件读取数据。 5282 5283**系统能力**:SystemCapability.FileManagement.File.FileIO 5284 5285**参数:** 5286 5287 | 参数名 | 类型 | 必填 | 说明 | 5288 | ------- | ----------- | ---- | ---------------------------------------- | 5289 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5290 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/> | 5291 5292**返回值:** 5293 5294 | 类型 | 说明 | 5295 | ------ | -------- | 5296 | number | 实际读取的长度。 | 5297 5298**错误码:** 5299 5300接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5301 5302**示例:** 5303 5304 ```ts 5305 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5306 let filePath = pathDir + "/test.txt"; 5307 let stream = fs.createStreamSync(filePath, "r+"); 5308 let readOption: ReadOptions = { 5309 offset: 5, 5310 length: 5 5311 }; 5312 let buf = new ArrayBuffer(4096); 5313 let num = stream.readSync(buf, readOption); 5314 stream.close(); 5315 ``` 5316 5317## File 5318 5319由open接口打开的File对象。 5320 5321**系统能力**:SystemCapability.FileManagement.File.FileIO 5322 5323### 属性 5324 5325| 名称 | 类型 | 只读 | 可写 | 说明 | 5326| ---- | ------ | ---- | ---- | ------- | 5327| fd | number | 是 | 否 | 打开的文件描述符。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 5328| path<sup>10+</sup> | string | 是 | 否 | 文件路径。 | 5329| name<sup>10+</sup> | string | 是 | 否 | 文件名。 | 5330 5331### getParent<sup>11+</sup> 5332 5333getParent(): string 5334 5335获取File对象对应文件父目录。 5336 5337**系统能力**:SystemCapability.FileManagement.File.FileIO 5338 5339**返回值:** 5340 5341 | 类型 | 说明 | 5342 | ---------------------------------- | ------ | 5343 | string | 返回父目录路径。 | 5344 5345**错误码:** 5346 5347接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5348 5349**示例:** 5350 5351 ```ts 5352 import { BusinessError } from '@kit.BasicServicesKit'; 5353 let filePath = pathDir + "/test.txt"; 5354 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5355 console.info('The parent path is: ' + file.getParent()); 5356 fs.closeSync(file); 5357 ``` 5358 5359### lock 5360 5361lock(exclusive?: boolean): Promise\<void> 5362 5363文件阻塞式施加共享锁或独占锁,使用Promise异步返回。 5364 5365**系统能力**:SystemCapability.FileManagement.File.FileIO 5366 5367**参数:** 5368 5369 | 参数名 | 类型 | 必填 | 说明 | 5370 | ------- | ----------- | ---- | ---------------------------------------- | 5371 | exclusive | boolean | 否 | 是否施加独占锁,默认false。 | 5372 5373**返回值:** 5374 5375 | 类型 | 说明 | 5376 | ---------------------------------- | ------ | 5377 | Promise<void> | Promise对象。无返回值。 | 5378 5379**错误码:** 5380 5381接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5382 5383**示例:** 5384 5385 ```ts 5386 import { BusinessError } from '@kit.BasicServicesKit'; 5387 let filePath = pathDir + "/test.txt"; 5388 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5389 file.lock(true).then(() => { 5390 console.log("lock file succeed"); 5391 }).catch((err: BusinessError) => { 5392 console.error("lock file failed with error message: " + err.message + ", error code: " + err.code); 5393 }).finally(() => { 5394 fs.closeSync(file); 5395 }); 5396 ``` 5397 5398### lock 5399 5400lock(exclusive?: boolean, callback: AsyncCallback\<void>): void 5401 5402文件阻塞式施加共享锁或独占锁,使Callback异步回调。 5403 5404**系统能力**:SystemCapability.FileManagement.File.FileIO 5405 5406**参数:** 5407 5408 | 参数名 | 类型 | 必填 | 说明 | 5409 | ------- | ----------- | ---- | ---------------------------------------- | 5410 | exclusive | boolean | 否 | 是否施加独占锁,默认false。 | 5411 | callback | AsyncCallback<void> | 是 | 异步文件上锁之后的回调。 | 5412 5413**错误码:** 5414 5415接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5416 5417**示例:** 5418 5419 ```ts 5420 import { BusinessError } from '@kit.BasicServicesKit'; 5421 let filePath = pathDir + "/test.txt"; 5422 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5423 file.lock(true, (err: BusinessError) => { 5424 if (err) { 5425 console.error("lock file failed with error message: " + err.message + ", error code: " + err.code); 5426 } else { 5427 console.log("lock file succeed"); 5428 } 5429 fs.closeSync(file); 5430 }); 5431 ``` 5432 5433### tryLock 5434 5435tryLock(exclusive?: boolean): void 5436 5437文件非阻塞式施加共享锁或独占锁。 5438 5439**系统能力**:SystemCapability.FileManagement.File.FileIO 5440 5441**参数:** 5442 5443 | 参数名 | 类型 | 必填 | 说明 | 5444 | ------- | ----------- | ---- | ---------------------------------------- | 5445 | exclusive | boolean | 否 | 是否施加独占锁,默认false。 | 5446 5447**错误码:** 5448 5449接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5450 5451**示例:** 5452 5453 ```ts 5454 let filePath = pathDir + "/test.txt"; 5455 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5456 file.tryLock(true); 5457 console.log("lock file succeed"); 5458 fs.closeSync(file); 5459 ``` 5460 5461### unlock 5462 5463unlock(): void 5464 5465以同步方式给文件解锁。 5466 5467**系统能力**:SystemCapability.FileManagement.File.FileIO 5468 5469**错误码:** 5470 5471接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5472 5473**示例:** 5474 5475 ```ts 5476 let filePath = pathDir + "/test.txt"; 5477 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5478 file.tryLock(true); 5479 file.unlock(); 5480 console.log("unlock file succeed"); 5481 fs.closeSync(file); 5482 ``` 5483 5484 ## fs.DfsListeners<sup>12+</sup> 5485 5486interface DfsListeners { 5487 onStatus(networkId: string, status: number): void 5488} 5489 5490事件监听类。创建DFSListener对象,用于监听分布式文件系统状态。 5491 5492**系统能力**:SystemCapability.FileManagement.File.FileIO 5493 5494### onStatus<sup>12+</sup> 5495 5496onStatus(networkId: string, status: number): void; 5497 5498事件回调类。参数由[connectDfs](#fsconnectdfs12)传入。 5499 5500**系统能力**:SystemCapability.FileManagement.File.FileIO 5501 5502**参数:** 5503 5504 | 参数名 | 类型 | 必填 | 说明 | 5505 | ---- | ------ | ---- | ---------------------------------------- | 5506 | networkId | string | 是 | 设备的网络Id。 | 5507 | status | number | 是 | 分布式文件系统的状态码(以connectDfs回调onStatus的特定错误码作为入参)。触发场景为connectDfs调用过程中出现对端设备异常,对应错误码为:<br/>- [13900046](errorcode-filemanagement.md#13900046):软件造成连接中断。 5508 5509## RandomAccessFile 5510 5511随机读写文件流。在调用RandomAccessFile的方法前,需要先通过createRandomAccess()方法(同步或异步)来构建一个RandomAccessFile实例。 5512 5513**系统能力**:SystemCapability.FileManagement.File.FileIO 5514 5515### 属性 5516 5517| 名称 | 类型 | 只读 | 可写 | 说明 | 5518| ----------- | ------ | ---- | ----- | ---------------- | 5519| fd | number | 是 | 否 | 打开的文件描述符。 | 5520| filePointer | number | 是 | 是 | RandomAccessFile对象的偏置指针。 | 5521 5522### setFilePointer<sup>10+</sup> 5523 5524setFilePointer(filePointer:number): void 5525 5526设置文件偏置指针。 5527 5528**系统能力**:SystemCapability.FileManagement.File.FileIO 5529 5530**参数:** 5531 5532 | 参数名 | 类型 | 必填 | 说明 | 5533 | ------- | ----------- | ---- | ----------------------------- | 5534 | filePointer | number | 是 | RandomAccessFile对象的偏置指针。 | 5535 5536**错误码:** 5537 5538接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5539 5540**示例:** 5541 5542 ```ts 5543 let filePath = pathDir + "/test.txt"; 5544 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5545 randomAccessFile.setFilePointer(1); 5546 randomAccessFile.close(); 5547 ``` 5548 5549 5550### close<sup>10+</sup> 5551 5552close(): void 5553 5554同步关闭RandomAccessFile对象。 5555 5556**系统能力**:SystemCapability.FileManagement.File.FileIO 5557 5558**错误码:** 5559 5560接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5561 5562**示例:** 5563 5564 ```ts 5565 let filePath = pathDir + "/test.txt"; 5566 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 5567 randomAccessFile.close(); 5568 ``` 5569 5570### write<sup>10+</sup> 5571 5572write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise<number> 5573 5574将数据写入文件,使用Promise异步返回。 5575 5576**系统能力**:SystemCapability.FileManagement.File.FileIO 5577 5578**参数:** 5579 5580 | 参数名 | 类型 | 必填 | 说明 | 5581 | ------- | ------------------------------- | ---- | ---------------------------------------- | 5582 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5583 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5584 5585**返回值:** 5586 5587 | 类型 | 说明 | 5588 | --------------------- | -------- | 5589 | Promise<number> | Promise对象。返回实际写入的长度。 | 5590 5591**错误码:** 5592 5593接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5594 5595**示例:** 5596 5597 ```ts 5598 import { BusinessError } from '@kit.BasicServicesKit'; 5599 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5600 let filePath = pathDir + "/test.txt"; 5601 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5602 let randomAccessFile = fs.createRandomAccessFileSync(file); 5603 let bufferLength: number = 4096; 5604 let writeOption: WriteOptions = { 5605 offset: 1, 5606 length: 5, 5607 encoding: 'utf-8' 5608 }; 5609 let arrayBuffer = new ArrayBuffer(bufferLength); 5610 randomAccessFile.write(arrayBuffer, writeOption).then((bytesWritten: number) => { 5611 console.info("randomAccessFile bytesWritten: " + bytesWritten); 5612 }).catch((err: BusinessError) => { 5613 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 5614 }).finally(() => { 5615 randomAccessFile.close(); 5616 fs.closeSync(file); 5617 }); 5618 5619 ``` 5620 5621### write<sup>10+</sup> 5622 5623write(buffer: ArrayBuffer | string, options?: WriteOptions, callback: AsyncCallback<number>): void 5624 5625将数据写入文件,使用callback异步回调。 5626 5627**系统能力**:SystemCapability.FileManagement.File.FileIO 5628 5629**参数:** 5630 5631 | 参数名 | 类型 | 必填 | 说明 | 5632 | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 5633 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5634 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5635 | callback | AsyncCallback<number> | 是 | 异步写入完成后执行的回调函数。 | 5636 5637**错误码:** 5638 5639接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5640 5641**示例:** 5642 5643 ```ts 5644 import { BusinessError } from '@kit.BasicServicesKit'; 5645 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5646 let filePath = pathDir + "/test.txt"; 5647 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5648 let randomAccessFile = fs.createRandomAccessFileSync(file); 5649 let bufferLength: number = 4096; 5650 let writeOption: WriteOptions = { 5651 offset: 1, 5652 length: bufferLength, 5653 encoding: 'utf-8' 5654 }; 5655 let arrayBuffer = new ArrayBuffer(bufferLength); 5656 randomAccessFile.write(arrayBuffer, writeOption, (err: BusinessError, bytesWritten: number) => { 5657 if (err) { 5658 console.error("write failed with error message: " + err.message + ", error code: " + err.code); 5659 } else { 5660 if (bytesWritten) { 5661 console.info("write succeed and size is:" + bytesWritten); 5662 } 5663 } 5664 randomAccessFile.close(); 5665 fs.closeSync(file); 5666 }); 5667 ``` 5668 5669### writeSync<sup>10+</sup> 5670 5671writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number 5672 5673以同步方法将数据写入文件。 5674 5675**系统能力**:SystemCapability.FileManagement.File.FileIO 5676 5677**参数:** 5678 5679 | 参数名 | 类型 | 必填 | 说明 | 5680 | ------- | ------------------------------- | ---- | ---------------------------------------- | 5681 | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | 5682 | options | [WriteOptions](#writeoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望写入文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始写。<br/>- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。| 5683 5684**返回值:** 5685 5686 | 类型 | 说明 | 5687 | ------ | -------- | 5688 | number | 实际写入的长度。 | 5689 5690**错误码:** 5691 5692接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5693 5694**示例:** 5695 5696 ```ts 5697 import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit'; 5698 let filePath = pathDir + "/test.txt"; 5699 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5700 let writeOption: WriteOptions = { 5701 offset: 5, 5702 length: 5, 5703 encoding: 'utf-8' 5704 }; 5705 let bytesWritten = randomAccessFile.writeSync("hello, world", writeOption); 5706 randomAccessFile.close(); 5707 ``` 5708 5709### read<sup>10+</sup> 5710 5711read(buffer: ArrayBuffer, options?: ReadOptions): Promise<number> 5712 5713从文件读取数据,使用Promise异步返回。 5714 5715**系统能力**:SystemCapability.FileManagement.File.FileIO 5716 5717**参数:** 5718 5719 | 参数名 | 类型 | 必填 | 说明 | 5720 | ------- | ----------- | ---- | ---------------------------------------- | 5721 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5722 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始读。 | 5723 5724**返回值:** 5725 5726 | 类型 | 说明 | 5727 | ---------------------------------- | ------ | 5728 | Promise<number> | Promise对象。返回读取的结果。 | 5729 5730**错误码:** 5731 5732接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5733 5734**示例:** 5735 5736 ```ts 5737 import { BusinessError } from '@kit.BasicServicesKit'; 5738 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5739 let filePath = pathDir + "/test.txt"; 5740 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5741 let randomAccessFile = fs.createRandomAccessFileSync(file); 5742 let bufferLength: number = 4096; 5743 let readOption: ReadOptions = { 5744 offset: 1, 5745 length: 5 5746 }; 5747 let arrayBuffer = new ArrayBuffer(bufferLength); 5748 randomAccessFile.read(arrayBuffer, readOption).then((readLength: number) => { 5749 console.info("randomAccessFile readLength: " + readLength); 5750 }).catch((err: BusinessError) => { 5751 console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 5752 }).finally(() => { 5753 randomAccessFile.close(); 5754 fs.closeSync(file); 5755 }); 5756 ``` 5757 5758### read<sup>10+</sup> 5759 5760read(buffer: ArrayBuffer, options?: ReadOptions, callback: AsyncCallback<number>): void 5761 5762从文件读取数据,使用callback异步回调。 5763 5764**系统能力**:SystemCapability.FileManagement.File.FileIO 5765 5766**参数:** 5767 5768 | 参数名 | 类型 | 必填 | 说明 | 5769 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 5770 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5771 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始读. | 5772 | callback | AsyncCallback<number> | 是 | 异步从流文件读取数据之后的回调。 | 5773 5774**错误码:** 5775 5776接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5777 5778**示例:** 5779 5780 ```ts 5781 import { BusinessError } from '@kit.BasicServicesKit'; 5782 import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; 5783 let filePath = pathDir + "/test.txt"; 5784 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5785 let randomAccessFile = fs.createRandomAccessFileSync(file); 5786 let length: number = 20; 5787 let readOption: ReadOptions = { 5788 offset: 1, 5789 length: 5 5790 }; 5791 let arrayBuffer = new ArrayBuffer(length); 5792 randomAccessFile.read(arrayBuffer, readOption, (err: BusinessError, readLength: number) => { 5793 if (err) { 5794 console.error("read failed with error message: " + err.message + ", error code: " + err.code); 5795 } else { 5796 if (readLength) { 5797 console.info("read succeed and size is:" + readLength); 5798 } 5799 } 5800 randomAccessFile.close(); 5801 fs.closeSync(file); 5802 }); 5803 ``` 5804 5805### readSync<sup>10+</sup> 5806 5807readSync(buffer: ArrayBuffer, options?: ReadOptions): number 5808 5809以同步方法从文件读取数据。 5810 5811**系统能力**:SystemCapability.FileManagement.File.FileIO 5812 5813**参数:** 5814 5815 | 参数名 | 类型 | 必填 | 说明 | 5816 | ------- | ----------- | ---- | ---------------------------------------- | 5817 | buffer | ArrayBuffer | 是 | 用于读取文件的缓冲区。 | 5818 | options | [ReadOptions](#readoptions11) | 否 | 支持如下选项:<br/>- length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>- offset,number类型,表示期望读取文文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始读。<br/> | 5819 5820**返回值:** 5821 5822 | 类型 | 说明 | 5823 | ------ | -------- | 5824 | number | 实际读取的长度。 | 5825 5826**错误码:** 5827 5828接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5829 5830**示例:** 5831 5832 ```ts 5833 let filePath = pathDir + "/test.txt"; 5834 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5835 let randomAccessFile = fs.createRandomAccessFileSync(file); 5836 let length: number = 4096; 5837 let arrayBuffer = new ArrayBuffer(length); 5838 let readLength = randomAccessFile.readSync(arrayBuffer); 5839 randomAccessFile.close(); 5840 fs.closeSync(file); 5841 ``` 5842 5843### getReadStream<sup>12+</sup> 5844 5845getReadStream(): ReadStream 5846 5847获取当前 RandomAccessFile 的一个 ReadStream 实例。 5848 5849**系统能力**:SystemCapability.FileManagement.File.FileIO 5850 5851**返回值:** 5852 5853 | 类型 | 说明 | 5854 | ------------------ | --------- | 5855 | [ReadStream](#readstream12) | 文件可读流。 | 5856 5857**示例:** 5858 5859 ```ts 5860 const filePath = pathDir + "/test.txt"; 5861 const randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5862 const rs = randomAccessFile.getReadStream(); 5863 rs.close(); 5864 randomAccessFile.close(); 5865 ``` 5866 5867### getWriteStream<sup>12+</sup> 5868 5869getWriteStream(): WriteStream 5870 5871获取当前 RandomAccessFile 的一个 WriteStream 实例。 5872 5873**系统能力**:SystemCapability.FileManagement.File.FileIO 5874 5875**返回值:** 5876 5877 | 类型 | 说明 | 5878 | ------------------ | --------- | 5879 | [WriteStream](#writestream12) | 文件可写流。 | 5880 5881**示例:** 5882 5883 ```ts 5884 const filePath = pathDir + "/test.txt"; 5885 const randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 5886 const ws = randomAccessFile.getWriteStream(); 5887 ws.close(); 5888 randomAccessFile.close(); 5889 ``` 5890 5891 5892## Watcher<sup>10+</sup> 5893 5894文件目录变化监听对象。由createWatcher接口获得。 5895 5896### start<sup>10+</sup> 5897 5898start(): void 5899 5900开启监听。 5901 5902**系统能力**:SystemCapability.FileManagement.File.FileIO 5903 5904**错误码:** 5905 5906接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5907 5908**示例:** 5909 5910 ```ts 5911 let filePath = pathDir + "/test.txt"; 5912 let watcher = fs.createWatcher(filePath, 0xfff, () => {}); 5913 watcher.start(); 5914 watcher.stop(); 5915 ``` 5916 5917### stop<sup>10+</sup> 5918 5919stop(): void 5920 5921停止监听,移除Watcher对象。 5922 5923**系统能力**:SystemCapability.FileManagement.File.FileIO 5924 5925**错误码:** 5926 5927接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 5928 5929**示例:** 5930 5931 ```ts 5932 let filePath = pathDir + "/test.txt"; 5933 let watcher = fs.createWatcher(filePath, 0xfff, () => {}); 5934 watcher.start(); 5935 watcher.stop(); 5936 ``` 5937 5938## OpenMode 5939 5940open接口flags参数常量。文件打开标签。 5941 5942**系统能力**:SystemCapability.FileManagement.File.FileIO 5943 5944| 名称 | 类型 | 值 | 说明 | 5945| ---- | ------ |---- | ------- | 5946| READ_ONLY | number | 0o0 | 只读打开。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 5947| WRITE_ONLY | number | 0o1 | 只写打开。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 5948| READ_WRITE | number | 0o2 | 读写打开。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 5949| CREATE | number | 0o100 | 若文件不存在,则创建文件。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 5950| TRUNC | number | 0o1000 | 如果文件存在且以只写或读写的方式打开文件,则将其长度裁剪为零。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 5951| APPEND | number | 0o2000 | 以追加方式打开,后续写将追加到文件末尾。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 5952| NONBLOCK | number | 0o4000 | 如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。 | 5953| DIR | number | 0o200000 | 如果path不指向目录,则出错。 | 5954| NOFOLLOW | number | 0o400000 | 如果path指向符号链接,则出错。 | 5955| SYNC | number | 0o4010000 | 以同步IO的方式打开文件。 | 5956 5957## Filter<sup>10+</sup> 5958 5959文件过滤配置项类型,支持listFile接口使用。 5960 5961**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 5962 5963**系统能力**:SystemCapability.FileManagement.File.FileIO 5964 5965| 名称 | 类型 | 必选 | 说明 | 5966| ----------- | --------------- | ------------------ | ------------------ | 5967| suffix | Array<string> | 否 | 文件后缀名完全匹配,各个关键词OR关系。 | 5968| displayName | Array<string> | 否 | 文件名模糊匹配,各个关键词OR关系。当前仅支持通配符*。 | 5969| mimeType | Array<string> | 否 | mime类型完全匹配,各个关键词OR关系。 | 5970| fileSizeOver | number | 否 | 文件大小匹配,大于等于指定大小的文件。 | 5971| lastModifiedAfter | number | 否 | 文件最近修改时间匹配,在指定时间点及之后的文件。 | 5972| excludeMedia | boolean | 否 | 是否排除Media中已有的文件。 | 5973 5974## ConflictFiles<sup>10+</sup> 5975 5976冲突文件信息,支持copyDir及moveDir接口使用。 5977 5978**系统能力**:SystemCapability.FileManagement.File.FileIO 5979 5980| 名称 | 类型 | 说明 | 5981| ----------- | --------------- | ------------------ | 5982| srcFile | string | 源冲突文件路径。 | 5983| destFile | string | 目标冲突文件路径。 | 5984 5985## Options<sup>11+</sup> 5986 5987可选项类型,支持readLines接口使用。 5988 5989**系统能力**:SystemCapability.FileManagement.File.FileIO 5990 5991| 名称 | 类型 | 说明 | 5992| ----------- | --------------- | ------------------ | 5993| encoding | string | 文件编码方式。可选项。 | 5994 5995## WhenceType<sup>11+</sup> 5996 5997枚举,文件偏移指针相对偏移位置类型,支持lseek接口使用。 5998 5999**系统能力**:SystemCapability.FileManagement.File.FileIO 6000 6001| 名称 | 值 | 说明 | 6002| ----------- | --------------- | ------------------ | 6003| SEEK_SET | 0 | 文件起始位置处。 | 6004| SEEK_CUR | 1 | 当前文件偏置指针位置处。 | 6005| SEEK_END | 2 | 文件末尾位置处。 | 6006 6007## LocationType<sup>11+</sup> 6008 6009枚举,文件位置,表示该文件是否在本地或者云端存在。 6010 6011**系统能力**:SystemCapability.FileManagement.File.FileIO 6012 6013| 名称 | 值 | 说明 | 6014| ----------- | --------------- | ------------------ | 6015| LOCAl | 1 | 文件在本地存在。 | 6016| CLOUD | 2 | 文件在云端存在。 | 6017 6018## AccessModeType<sup>12+</sup> 6019 6020枚举,表示需要校验的具体权限。若不填,默认校验文件是否存在。 6021 6022**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 6023 6024**系统能力**:SystemCapability.FileManagement.File.FileIO 6025 6026| 名称 | 值 | 说明 | 6027| ----------- | --------------- | ------------------ | 6028| EXIST | 0 | 文件是否存在。 | 6029| WRITE | 2 | 文件是否具有写入权限。 | 6030| READ | 4 | 文件是否具有读取权限。 | 6031| READ_WRITE | 6 | 文件是否具有读写权限。 | 6032 6033## AccessFlagType<sup>12+</sup> 6034 6035枚举,表示需要校验的文件位置。 6036 6037**系统能力**:SystemCapability.FileManagement.File.FileIO 6038 6039| 名称 | 值 | 说明 | 6040| ----------- | --------------- | ------------------ | 6041| LOCAL | 0 | 文件是否在本地。 | 6042 6043## ReadOptions<sup>11+</sup> 6044 6045可选项类型,支持read接口使用。 6046 6047**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 6048 6049**系统能力**:SystemCapability.FileManagement.File.FileIO 6050 6051| 名称 | 类型 | 必选 | 说明 | 6052| ----------- | --------------- | ------------------ |------------------ | 6053| length | number | 否 | 期望读取数据的长度,单位为字节。可选,默认缓冲区长度。 | 6054| offset | number | 否 | 期望读取文件位置,单位为字节(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始读。 | 6055 6056## ReadTextOptions<sup>11+</sup> 6057 6058可选项类型,支持readText接口使用,ReadTextOptions继承至[ReadOptions](#readoptions11)。 6059 6060**系统能力**:SystemCapability.FileManagement.File.FileIO 6061 6062| 名称 | 类型 | 必选 | 说明 | 6063| ----------- | --------------- | ------------------ | ------------------ | 6064| length | number | 否 | 期望读取数据的长度,单位为字节。可选,默认文件长度。 | 6065| offset | number | 否 | 期望读取文件的位置,单位为字节。可选,默认从当前位置开始读取。 | 6066| encoding | string | 否 | 当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。 <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 6067 6068## WriteOptions<sup>11+</sup> 6069 6070可选项类型,支持write接口使用,WriteOptions继承至[Options](#options11)。 6071 6072**系统能力**:SystemCapability.FileManagement.File.FileIO 6073 6074| 名称 | 类型 | 必选 | 说明 | 6075| ----------- | --------------- | ------------------ | ------------------ | 6076| length | number | 否 | 期望写入数据的长度,单位为字节。可选,默认缓冲区长度。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 6077| offset | number | 否 | 期望写入文件位置,单位为字节(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始写。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 6078| encoding | string | 否 | 当数据是string类型时有效,表示数据的编码方式。默认 'utf-8'。仅支持 'utf-8'。 | 6079 6080## ListFileOptions<sup>11+</sup> 6081 6082可选项类型,支持listFile接口使用。 6083 6084**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。 6085 6086**系统能力**:SystemCapability.FileManagement.File.FileIO 6087 6088| 名称 | 类型 | 必选 | 说明 | 6089| ----------- | --------------- | ------------------ | ------------------ | 6090| recursion | boolean | 否 | 是否递归子目录下文件名。可选,默认为false。当recursion为false时,返回当前目录下满足过滤要求的文件名及文件夹名。当recursion为true时,返回此目录下所有满足过滤要求的文件的相对路径(以/开头)。 | 6091| listNum | number | 否 | 列出文件名数量。可选,当设置0时,列出所有文件,默认为0。 | 6092| filter | [Filter](#filter10) | 否 | 文件过滤配置项类型。 可选,设置文件的过滤条件。 | 6093 6094## ReadStream<sup>12+</sup> 6095 6096文件可读流,需要先通过[fs.createReadStream](#fscreatereadstream12)方法来构建一个ReadStream实例。ReadStream继承自数据流基类[stream](../apis-arkts/js-apis-stream.md#readable)。 6097 6098**规格**:ReadStream读到的数据为解码后的字符串,其编码格式当前仅支持'utf-8'。 6099 6100### 属性 6101 6102| 名称 | 类型 | 只读 | 可写 | 说明 | 6103| ------ | ------ | ---- | ---- | ---------------------------------------- | 6104| bytesRead | number | 是 | 否 | 可读流已经读取的字节数。 | 6105| path | string | 是 | 否 | 当前可读流对应的文件路径。 | 6106 6107### Seek 6108 6109seek(offset: number, whence?: WhenceType): number 6110 6111 6112调整可读流偏置指针位置。 6113 6114**系统能力**:SystemCapability.FileManagement.File.FileIO 6115 6116**参数:** 6117 6118 | 参数名 | 类型 | 必填 | 说明 | 6119 | ------ | ------ | ---- | --------------------------- | 6120 | offset | number | 是 | 相对偏移位置,单位为字节。 | 6121 | whence | [WhenceType](#whencetype11) | 否 | 偏移指针相对位置类型。默认值:SEEK_SET,文件起始位置处。 | 6122 6123**返回值:** 6124 6125 | 类型 | 说明 | 6126 | --------------------- | ---------- | 6127 | number | 当前可读流偏置指针位置(相对于文件头的偏移量,单位为字节)。 | 6128 6129**错误码:** 6130 6131接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 6132 6133**示例:** 6134 6135 ```ts 6136 const filePath = pathDir + "/test.txt"; 6137 const rs = fs.createReadStream(filePath); 6138 const curOff = rs.seek(5, fs.WhenceType.SEEK_SET); 6139 console.info(`current offset is ${curOff}`); 6140 rs.close(); 6141 ``` 6142 6143### close 6144 6145close(): void 6146 6147关闭可读流。 6148 6149**系统能力**:SystemCapability.FileManagement.File.FileIO 6150 6151**错误码:** 6152 6153接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 6154 6155**示例:** 6156 6157 ```ts 6158 const filePath = pathDir + "/test.txt"; 6159 const rs = fs.createReadStream(filePath); 6160 rs.close(); 6161 ``` 6162 6163## WriteStream<sup>12+</sup> 6164 6165文件可写流,需要先通过[fs.createWriteStream](#fscreatewritestream12)方法来构建一个WriteStream实例。WriteStream继承自数据流基类[stream](../apis-arkts/js-apis-stream.md#writable)。 6166 6167### 属性 6168 6169| 名称 | 类型 | 只读 | 可写 | 说明 | 6170| ------ | ------ | ---- | ---- | ---------------------------------------- | 6171| bytesWritten | number | 是 | 否 | 可写流已经写入的字节数。 | 6172| path | string | 是 | 否 | 当前可写流对应的文件路径。 | 6173 6174### Seek 6175 6176seek(offset: number, whence?: WhenceType): number; 6177 6178调整可写流偏置指针位置。 6179 6180**系统能力**:SystemCapability.FileManagement.File.FileIO 6181 6182**参数:** 6183 6184 | 参数名 | 类型 | 必填 | 说明 | 6185 | ------ | ------ | ---- | --------------------------- | 6186 | offset | number | 是 | 相对偏移位置,单位为字节。 | 6187 | whence | [WhenceType](#whencetype11) | 否 | 偏移指针相对位置类型。默认值:SEEK_SET,文件起始位置处。 | 6188 6189**返回值:** 6190 6191 | 类型 | 说明 | 6192 | --------------------- | ---------- | 6193 | number | 当前可写流偏置指针位置(相对于文件头的偏移量,单位为字节)。 | 6194 6195**错误码:** 6196 6197接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 6198 6199**示例:** 6200 6201 ```ts 6202 const filePath = pathDir + "/test.txt"; 6203 const ws = fs.createWriteStream(filePath); 6204 const curOff = ws.seek(5, fs.WhenceType.SEEK_SET); 6205 console.info(`current offset is ${curOff}`); 6206 ws.close(); 6207 ``` 6208 6209### close 6210 6211close(): void 6212 6213关闭可写流。 6214 6215**系统能力**:SystemCapability.FileManagement.File.FileIO 6216 6217**错误码:** 6218 6219接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。 6220 6221**示例:** 6222 6223 ```ts 6224 const filePath = pathDir + "/test.txt"; 6225 const ws = fs.createWriteStream(filePath); 6226 ws.close(); 6227 ``` 6228 6229## RandomAccessFileOptions<sup>12+</sup> 6230 6231可选项类型,支持 createRandomAccessFile 接口使用。 6232 6233**系统能力**:SystemCapability.FileManagement.File.FileIO 6234 6235| 名称 | 类型 | 必选 | 说明 | 6236| ----------- | --------------- | ------------------ | ------------------ | 6237| start | number | 否 | 表示期望读取文件的位置,单位为字节。可选,默认从当前位置开始读。 | 6238| end | number | 否 | 表示期望读取结束的位置,单位为字节。可选,默认文件末尾。 | 6239 6240## ReadStreamOptions<sup>12+</sup> 6241 6242可选项类型,支持 createReadStream 接口使用。 6243 6244**系统能力**:SystemCapability.FileManagement.File.FileIO 6245 6246| 名称 | 类型 | 必选 | 说明 | 6247| ----------- | --------------- | ------------------ | ------------------ | 6248| start | number | 否 | 表示期望读取文件的位置,单位为字节。可选,默认从当前位置开始读。 | 6249| end | number | 否 | 表示期望读取结束的位置,单位为字节。可选,默认文件末尾。 | 6250 6251## WriteStreamOptions<sup>12+</sup> 6252 6253可选项类型,支持 createWriteStream 接口使用。 6254 6255**系统能力**:SystemCapability.FileManagement.File.FileIO 6256 6257| 名称 | 类型 | 必选 | 说明 | 6258| ----------- | --------------- | ------------------ | ------------------ | 6259| start | number | 否 | 表示期望写入文件的位置,单位为字节。可选,默认文件起始位置。 | 6260| mode | number | 否 | 创建文件可写流的[选项](#openmode),必须指定如下选项中的一个,默认只写方式创建:<br/>- OpenMode.READ_ONLY(0o0):只读。<br/>- OpenMode.WRITE_ONLY(0o1):只写。<br/>- OpenMode.READ_WRITE(0o2):读写。<br/>给定如下功能选项,以按位或的方式追加,默认不给定任何额外选项:<br/>- OpenMode.CREATE(0o100):若文件不存在,则创建文件。<br/>- OpenMode.TRUNC(0o1000):如果文件存在且文件具有写权限,则将其长度裁剪为零。<br/>- OpenMode.APPEND(0o2000):以追加方式打开,后续写将追加到文件末尾。<br/>- OpenMode.NONBLOCK(0o4000):如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。<br/>- OpenMode.DIR(0o200000):如果path不指向目录,则出错。不允许附加写权限。<br/>- OpenMode.NOFOLLOW(0o400000):如果path指向符号链接,则出错。<br/>- OpenMode.SYNC(0o4010000):以同步IO的方式打开文件。 | 6261