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