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