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