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