1# @ohos.file.fs (File Management) 2 3The **fs** module provides APIs for file operations, including basic file management, directory management, file information statistics, and data read and write 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**Stage Model** 20 21 ```ts 22 import UIAbility from '@ohos.app.ability.UIAbility'; 23 import window from '@ohos.window'; 24 25 export default class EntryAbility extends UIAbility { 26 onWindowStageCreate(windowStage: window.WindowStage) { 27 let context = this.context; 28 let pathDir = context.filesDir; 29 } 30 } 31 ``` 32 33FA Model 34 35 ```js 36 import featureAbility from '@ohos.ability.featureAbility'; 37 38 let context = featureAbility.getContext(); 39 context.getFilesDir().then((data) => { 40 let pathDir = data; 41 }) 42 ``` 43 44For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context). 45 46## fs.stat 47 48stat(file: string|number): Promise<Stat> 49 50Obtains detailed file information. This API uses a promise to return the result. 51 52**System capability**: SystemCapability.FileManagement.File.FileIO 53 54**Parameters** 55 56| Name| Type | Mandatory| Description | 57| ------ | ------ | ---- | -------------------------- | 58| file | string\|number | Yes | Application sandbox path or file descriptor (FD) of the file.| 59 60**Return value** 61 62 | Type | Description | 63 | ---------------------------- | ---------- | 64 | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| 65 66**Error codes** 67 68For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 69 70**Example** 71 72 ```ts 73 import { BusinessError } from '@ohos.base'; 74 let filePath = pathDir + "/test.txt"; 75 fs.stat(filePath).then((stat: fs.Stat) => { 76 console.info("get file info succeed, the size of file is " + stat.size); 77 }).catch((err: BusinessError) => { 78 console.info("get file info failed with error message: " + err.message + ", error code: " + err.code); 79 }); 80 ``` 81 82## fs.stat 83 84stat(file: string|number, callback: AsyncCallback<Stat>): void 85 86Obtains detailed file information. This API uses an asynchronous callback to return the result. 87 88**System capability**: SystemCapability.FileManagement.File.FileIO 89 90**Parameters** 91 92| Name | Type | Mandatory| Description | 93| -------- | ---------------------------------- | ---- | ------------------------------ | 94| file | string\|number | Yes | Application sandbox path or FD of the file. | 95| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| 96 97**Error codes** 98 99For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 100 101**Example** 102 103 ```ts 104 import { BusinessError } from '@ohos.base'; 105 fs.stat(pathDir, (err: BusinessError, stat: fs.Stat) => { 106 if (err) { 107 console.info("get file info failed with error message: " + err.message + ", error code: " + err.code); 108 } else { 109 console.info("get file info succeed, the size of file is " + stat.size); 110 } 111 }); 112 ``` 113 114## fs.statSync 115 116statSync(file: string|number): Stat 117 118Obtains detailed file information synchronously. 119 120**System capability**: SystemCapability.FileManagement.File.FileIO 121 122**Parameters** 123 124| Name| Type | Mandatory| Description | 125| ------ | ------ | ---- | -------------------------- | 126| file | string\|number | Yes | Application sandbox path or file descriptor (FD) of the file.| 127 128**Return value** 129 130 | Type | Description | 131 | ------------- | ---------- | 132 | [Stat](#stat) | File information obtained.| 133 134**Error codes** 135 136For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 137 138**Example** 139 140 ```ts 141 let stat = fs.statSync(pathDir); 142 console.info("get file info succeed, the size of file is " + stat.size); 143 ``` 144 145## fs.access 146 147access(path: string): Promise<boolean> 148 149Checks whether a file exists. This API uses a promise to return the result. 150 151**System capability**: SystemCapability.FileManagement.File.FileIO 152 153**Parameters** 154 155| Name| Type | Mandatory| Description | 156| ------ | ------ | ---- | ------------------------------------------------------------ | 157| path | string | Yes | Application sandbox path of the file. | 158 159**Return value** 160 161 | Type | Description | 162 | ------------------- | ---------------------------- | 163 | Promise<boolean> | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.| 164 165**Error codes** 166 167For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 168 169**Example** 170 171 ```ts 172 import { BusinessError } from '@ohos.base'; 173 let filePath = pathDir + "/test.txt"; 174 fs.access(filePath).then((res: boolean) => { 175 if (res) { 176 console.info("file exists"); 177 } 178 }).catch((err: BusinessError) => { 179 console.info("access failed with error message: " + err.message + ", error code: " + err.code); 180 }); 181 ``` 182 183## fs.access 184 185access(path: string, callback: AsyncCallback<boolean>): void 186 187Checks whether a file exists. This API uses an asynchronous callback to return the result. 188 189**System capability**: SystemCapability.FileManagement.File.FileIO 190 191**Parameters** 192 193| Name | Type | Mandatory| Description | 194| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 195| path | string | Yes | Application sandbox path of the file. | 196| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the file exists; the value **false** means the opposite.| 197 198**Error codes** 199 200For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 201 202**Example** 203 204 ```ts 205 import { BusinessError } from '@ohos.base'; 206 let filePath = pathDir + "/test.txt"; 207 fs.access(filePath, (err: BusinessError, res: boolean) => { 208 if (err) { 209 console.info("access failed with error message: " + err.message + ", error code: " + err.code); 210 } else { 211 if (res) { 212 console.info("file exists"); 213 } 214 } 215 }); 216 ``` 217 218## fs.accessSync 219 220accessSync(path: string): boolean 221 222Checks whether a file exists. This API returns the result synchronously. 223 224**System capability**: SystemCapability.FileManagement.File.FileIO 225 226**Parameters** 227 228| Name| Type | Mandatory| Description | 229| ------ | ------ | ---- | ------------------------------------------------------------ | 230| path | string | Yes | Application sandbox path of the file. | 231 232**Return value** 233 234 | Type | Description | 235 | ------------------- | ---------------------------- | 236 | boolean | Returns **true** if the file exists; returns **false** otherwise.| 237 238**Error codes** 239 240For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 241 242**Example** 243 244 ```ts 245 import { BusinessError } from '@ohos.base'; 246 let filePath = pathDir + "/test.txt"; 247 try { 248 let res = fs.accessSync(filePath); 249 if (res) { 250 console.info("file exists"); 251 } 252 } catch(error) { 253 let err: BusinessError = error as BusinessError; 254 console.info("accessSync failed with error message: " + err.message + ", error code: " + err.code); 255 } 256 ``` 257 258 259## fs.close 260 261close(file: number|File): Promise<void> 262 263Closes a file. This API uses a promise to return the result. 264 265**System capability**: SystemCapability.FileManagement.File.FileIO 266 267**Parameters** 268 269 | Name | Type | Mandatory | Description | 270 | ---- | ------ | ---- | ------------ | 271 | file | number\|[File](#file) | Yes | File object or FD of the file to close.| 272 273**Return value** 274 275 | Type | Description | 276 | ------------------- | ---------------------------- | 277 | Promise<void> | Promise that returns no value.| 278 279**Error codes** 280 281For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 282 283**Example** 284 285 ```ts 286 import { BusinessError } from '@ohos.base'; 287 let filePath = pathDir + "/test.txt"; 288 let file = fs.openSync(filePath); 289 fs.close(file).then(() => { 290 console.info("File closed"); 291 }).catch((err: BusinessError) => { 292 console.info("close file failed with error message: " + err.message + ", error code: " + err.code); 293 }); 294 ``` 295 296## fs.close 297 298close(file: number|File, callback: AsyncCallback<void>): void 299 300Closes a file. This API uses an asynchronous callback to return the result. 301 302**System capability**: SystemCapability.FileManagement.File.FileIO 303 304**Parameters** 305 306 | Name | Type | Mandatory | Description | 307 | -------- | ------------------------- | ---- | ------------ | 308 | file | number\|[File](#file) | Yes | File object or FD of the file to close.| 309 | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is closed.| 310 311**Error codes** 312 313For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 314 315**Example** 316 317 ```ts 318 import { BusinessError } from '@ohos.base'; 319 let filePath = pathDir + "/test.txt"; 320 let file = fs.openSync(filePath); 321 fs.close(file, (err: BusinessError) => { 322 if (err) { 323 console.info("close file failed with error message: " + err.message + ", error code: " + err.code); 324 } else { 325 console.info("close file success"); 326 } 327 }); 328 ``` 329 330## fs.closeSync 331 332closeSync(file: number|File): void 333 334Closes a file. This API returns the result synchronously. 335 336**System capability**: SystemCapability.FileManagement.File.FileIO 337 338**Parameters** 339 340 | Name | Type | Mandatory | Description | 341 | ---- | ------ | ---- | ------------ | 342 | file | number\|[File](#file) | Yes | File object or FD of the file to close.| 343 344**Error codes** 345 346For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 347 348**Example** 349 350 ```ts 351 let filePath = pathDir + "/test.txt"; 352 let file = fs.openSync(filePath); 353 fs.closeSync(file); 354 ``` 355 356## fs.copyFile 357 358copyFile(src: string|number, dest: string|number, mode?: number): Promise<void> 359 360Copies a file. This API uses a promise to return the result. 361 362**System capability**: SystemCapability.FileManagement.File.FileIO 363 364**Parameters** 365 366 | Name | Type | Mandatory | Description | 367 | ---- | -------------------------- | ---- | ---------------------------------------- | 368 | src | string\|number | Yes | Path or FD of the file to copy. | 369 | dest | string\|number | Yes | Destination path of the file or FD of the file created. | 370 | 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.| 371 372**Return value** 373 374 | Type | Description | 375 | ------------------- | ---------------------------- | 376 | Promise<void> | Promise that returns no value.| 377 378**Error codes** 379 380For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 381 382**Example** 383 384 ```ts 385 import { BusinessError } from '@ohos.base'; 386 let srcPath = pathDir + "/srcDir/test.txt"; 387 let dstPath = pathDir + "/dstDir/test.txt"; 388 fs.copyFile(srcPath, dstPath).then(() => { 389 console.info("copy file succeed"); 390 }).catch((err: BusinessError) => { 391 console.info("copy file failed with error message: " + err.message + ", error code: " + err.code); 392 }); 393 ``` 394 395## fs.copyFile 396 397copyFile(src: string|number, dest: string|number, mode?: number, callback: AsyncCallback<void>): void 398 399Copies a file. This API uses an asynchronous callback to return the result. 400 401**System capability**: SystemCapability.FileManagement.File.FileIO 402 403**Parameters** 404 405 | Name | Type | Mandatory | Description | 406 | -------- | -------------------------- | ---- | ---------------------------------------- | 407 | src | string\|number | Yes | Path or FD of the file to copy. | 408 | dest | string\|number | Yes | Destination path of the file or FD of the file created. | 409 | 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.| 410 | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is copied. | 411 412**Error codes** 413 414For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 415 416**Example** 417 418 ```ts 419 import { BusinessError } from '@ohos.base'; 420 let srcPath = pathDir + "/srcDir/test.txt"; 421 let dstPath = pathDir + "/dstDir/test.txt"; 422 fs.copyFile(srcPath, dstPath, (err: BusinessError) => { 423 if (err) { 424 console.info("copy file failed with error message: " + err.message + ", error code: " + err.code); 425 } else { 426 console.info("copy file success"); 427 } 428 }); 429 ``` 430 431 432## fs.copyFileSync 433 434copyFileSync(src: string|number, dest: string|number, mode?: number): void 435 436Copies a file. This API returns the result synchronously. 437 438**System capability**: SystemCapability.FileManagement.File.FileIO 439 440**Parameters** 441 442 | Name | Type | Mandatory | Description | 443 | ---- | -------------------------- | ---- | ---------------------------------------- | 444 | src | string\|number | Yes | Path or FD of the file to copy. | 445 | dest | string\|number | Yes | Destination path of the file or FD of the file created. | 446 | 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.| 447 448**Error codes** 449 450For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 451 452**Example** 453 454 ```ts 455 let srcPath = pathDir + "/srcDir/test.txt"; 456 let dstPath = pathDir + "/dstDir/test.txt"; 457 fs.copyFileSync(srcPath, dstPath); 458 ``` 459 460## fs.copyDir<sup>10+</sup> 461 462copyDir(src: string, dest: string, mode?: number): Promise\<void> 463 464Copies a directory to the specified directory. This API uses a promise to return the result. 465 466**System capability**: SystemCapability.FileManagement.File.FileIO 467 468**Parameters** 469 470 | Name | Type | Mandatory | Description | 471 | ------ | ------ | ---- | --------------------------- | 472 | src | string | Yes | Application sandbox path of the directory to copy.| 473 | dest | string | Yes | Application sandbox path of the destination directory.| 474 | 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 directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.<br>- **1**: Forcibly overwrite the files with the same name in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.| 475 476**Return value** 477 478 | Type | Description | 479 | ------------------- | ---------------------------- | 480 | Promise<void> | Promise that returns no value.| 481 482**Error codes** 483 484For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 485 486**Example** 487 488 ```ts 489 import { BusinessError } from '@ohos.base'; 490 // Copy srcPath to destPath. 491 let srcPath = pathDir + "/srcDir/"; 492 let destPath = pathDir + "/destDir/"; 493 fs.copyDir(srcPath, destPath, 0).then(() => { 494 console.info("copy directory succeed"); 495 }).catch((err: BusinessError) => { 496 console.info("copy directory failed with error message: " + err.message + ", error code: " + err.code); 497 }); 498 ``` 499 500## fs.copyDir<sup>10+</sup> 501 502copyDir(src: string, dest: string, mode?: number, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 503 504Copies a directory to the specified directory. This API uses an asynchronous callback to return the result. 505 506**System capability**: SystemCapability.FileManagement.File.FileIO 507 508**Parameters** 509 510 | Name | Type | Mandatory | Description | 511 | ------ | ------ | ---- | --------------------------- | 512 | src | string | Yes | Application sandbox path of the directory to copy.| 513 | dest | string | Yes | Application sandbox path of the destination directory.| 514 | 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 directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.<br>- **1**: Forcibly overwrite the files with the same name in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.| 515 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | Yes | Callback invoked immediately after the directory is copied. | 516 517**Error codes** 518 519For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 520 521**Example** 522 523 ```ts 524 import { BusinessError } from '@ohos.base'; 525 import fs, { ConflictFiles } from '@ohos.file.fs'; 526 // Copy srcPath to destPath. 527 let srcPath = pathDir + "/srcDir/"; 528 let destPath = pathDir + "/destDir/"; 529 fs.copyDir(srcPath, destPath, 0, (err: BusinessError, data: Array<ConflictFiles>) => { 530 if (err && err.code == 13900015) { 531 for (let i = 0; i < data.length; i++) { 532 console.info("copy directory failed with conflicting files: " + data[i].srcFile + " " + data[i].destFile); 533 } 534 } else if (err) { 535 console.info("copy directory failed with error message: " + err.message + ", error code: " + err.code); 536 } else { 537 console.info("copy directory succeed"); 538 } 539 }); 540 ``` 541 542## fs.copyDirSync<sup>10+</sup> 543 544copyDirSync(src: string, dest: string, mode?: number): void 545 546Copies a directory. This API returns the result synchronously. 547 548**System capability**: SystemCapability.FileManagement.File.FileIO 549 550**Parameters** 551 552 | Name | Type | Mandatory | Description | 553 | ------ | ------ | ---- | --------------------------- | 554 | src | string | Yes | Application sandbox path of the directory to copy.| 555 | dest | string | Yes | Application sandbox path of the destination directory.| 556 | 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 directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.<br>- **1**: Forcibly overwrite the files with the same name in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.| 557 558**Error codes** 559 560For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 561 562**Example** 563 564 ```ts 565 import { BusinessError } from '@ohos.base'; 566 // Copy srcPath to destPath. 567 let srcPath = pathDir + "/srcDir/"; 568 let destPath = pathDir + "/destDir/"; 569 try { 570 fs.copyDirSync(srcPath, destPath, 0); 571 console.info("copy directory succeed"); 572 } catch (error) { 573 let err: BusinessError = error as BusinessError; 574 console.info("copy directory failed with error message: " + err.message + ", error code: " + err.code); 575 } 576 ``` 577 578## fs.dup<sup>10+</sup> 579 580dup(fd: number): File 581 582Opens a **File** object based on the specified FD. 583 584**System capability**: SystemCapability.FileManagement.File.FileIO 585 586**Parameters** 587 588 | Name | Type | Mandatory | Description | 589 | ------ | ------ | ---- | --------------------------- | 590 | fd | number | Yes | FD of the file.| 591 592**Return value** 593 594 | Type | Description | 595 | ------------------- | ---------------------------- | 596 | [File](#file) | File object opened.| 597 598**Error codes** 599 600For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 601 602**Example** 603 604 ```ts 605 // convert fd to file 606 let fd: number = 0; // fd comes from other modules 607 let file = fs.dup(fd); 608 console.info("The name of the file is " + file.name); 609 fs.closeSync(file); 610 ``` 611 612 613## fs.mkdir 614 615mkdir(path: string): Promise<void> 616 617Creates a directory. This API uses a promise to return the result. 618 619**System capability**: SystemCapability.FileManagement.File.FileIO 620 621**Parameters** 622 623| Name| Type | Mandatory| Description | 624| ------ | ------ | ---- | ------------------------------------------------------------ | 625| path | string | Yes | Application sandbox path of the directory. | 626 627**Return value** 628 629 | Type | Description | 630 | ------------------- | ---------------------------- | 631 | Promise<void> | Promise that returns no value.| 632 633**Error codes** 634 635For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 636 637**Example** 638 639 ```ts 640 import { BusinessError } from '@ohos.base'; 641 let dirPath = pathDir + "/testDir"; 642 fs.mkdir(dirPath).then(() => { 643 console.info("Directory created"); 644 }).catch((err: BusinessError) => { 645 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 646 }); 647 ``` 648 649## fs.mkdir 650 651mkdir(path: string, callback: AsyncCallback<void>): void 652 653Creates a directory. This API uses an asynchronous callback to return the result. 654 655**System capability**: SystemCapability.FileManagement.File.FileIO 656 657**Parameters** 658 659| Name | Type | Mandatory| Description | 660| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 661| path | string | Yes | Application sandbox path of the directory. | 662| callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | 663 664**Error codes** 665 666For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 667 668**Example** 669 670 ```ts 671 import { BusinessError } from '@ohos.base'; 672 let dirPath = pathDir + "/testDir"; 673 fs.mkdir(dirPath, (err: BusinessError) => { 674 if (err) { 675 console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); 676 } else { 677 console.info("mkdir success"); 678 } 679 }); 680 ``` 681 682## fs.mkdirSync 683 684mkdirSync(path: string): void 685 686Creates a directory. This API returns the result synchronously. 687 688**System capability**: SystemCapability.FileManagement.File.FileIO 689 690**Parameters** 691 692| Name| Type | Mandatory| Description | 693| ------ | ------ | ---- | ------------------------------------------------------------ | 694| path | string | Yes | Application sandbox path of the directory. | 695 696**Error codes** 697 698For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 699 700**Example** 701 702 ```ts 703 let dirPath = pathDir + "/testDir"; 704 fs.mkdirSync(dirPath); 705 ``` 706 707## fs.open 708 709open(path: string, mode?: number): Promise<File> 710 711Opens a file. This API uses a promise to return the result. File uniform resource identifiers (URIs) are supported. 712 713**System capability**: SystemCapability.FileManagement.File.FileIO 714 715**Parameters** 716 717| Name| Type | Mandatory| Description | 718| ------ | ------ | ---- | ------------------------------------------------------------ | 719| path | string | Yes | Application sandbox path or URI of the file. | 720| 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.| 721 722**Return value** 723 724 | Type | Description | 725 | --------------------- | ----------- | 726 | Promise<[File](#file)> | Promise used to return the **File** object.| 727 728**Error codes** 729 730For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 731 732**Example** 733 734 ```ts 735 import { BusinessError } from '@ohos.base'; 736 let filePath = pathDir + "/test.txt"; 737 fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file: fs.File) => { 738 console.info("file fd: " + file.fd); 739 fs.closeSync(file); 740 }).catch((err: BusinessError) => { 741 console.info("open file failed with error message: " + err.message + ", error code: " + err.code); 742 }); 743 ``` 744 745 746## fs.open 747 748open(path: string, mode?: number, callback: AsyncCallback<File>): void 749 750Opens a file. This API uses an asynchronous callback to return the result. File URIs are supported. 751 752**System capability**: SystemCapability.FileManagement.File.FileIO 753 754**Parameters** 755 756| Name | Type | Mandatory| Description | 757| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 758| path | string | Yes | Application sandbox path or URI of the file. | 759| 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.| 760 761**Error codes** 762 763For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 764 765**Example** 766 767 ```ts 768 import { BusinessError } from '@ohos.base'; 769 let filePath = pathDir + "/test.txt"; 770 fs.open(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE, (err: BusinessError, file: fs.File) => { 771 if (err) { 772 console.info("open failed with error message: " + err.message + ", error code: " + err.code); 773 } else { 774 console.info("file fd: " + file.fd); 775 } 776 fs.closeSync(file); 777 }); 778 ``` 779 780## fs.openSync 781 782openSync(path: string, mode?: number): File 783 784Opens a file. File URIs are supported. This API returns the result synchronously. 785 786**System capability**: SystemCapability.FileManagement.File.FileIO 787 788**Parameters** 789 790| Name| Type | Mandatory| Description | 791| ------ | ------ | ---- | ------------------------------------------------------------ | 792| path | string | Yes | Application sandbox path or URI of the file. | 793| 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.| 794 795**Return value** 796 797 | Type | Description | 798 | ------ | ----------- | 799 | [File](#file) | File object opened.| 800 801**Error codes** 802 803For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 804 805**Example** 806 807 ```ts 808 let filePath = pathDir + "/test.txt"; 809 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 810 console.info("file fd: " + file.fd); 811 fs.closeSync(file); 812 ``` 813 814## fs.read 815 816read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise<number> 817 818Reads data from a file. This API uses a promise to return the result. 819 820**System capability**: SystemCapability.FileManagement.File.FileIO 821 822**Parameters** 823 824| Name | Type | Mandatory| Description | 825| ------- | ----------- | ---- | ------------------------------------------------------------ | 826| fd | number | Yes | FD of the file. | 827| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | 828| options | Object | 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.| 829 830**Return value** 831 832 | Type | Description | 833 | ---------------------------------- | ------ | 834 | Promise<number> | Promise used to return the data read.| 835 836**Error codes** 837 838For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 839 840**Example** 841 842 ```ts 843 import { BusinessError } from '@ohos.base'; 844 import buffer from '@ohos.buffer'; 845 let filePath = pathDir + "/test.txt"; 846 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 847 let arrayBuffer = new ArrayBuffer(4096); 848 fs.read(file.fd, arrayBuffer).then((readLen: number) => { 849 console.info("Read file data successfully"); 850 let buf = buffer.from(arrayBuffer, 0, readLen); 851 console.info(`The content of file: ${buf.toString()}`); 852 }).catch((err: BusinessError) => { 853 console.info("read file data failed with error message: " + err.message + ", error code: " + err.code); 854 }).finally(() => { 855 fs.closeSync(file); 856 }); 857 ``` 858 859## fs.read 860 861read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }, callback: AsyncCallback<number>): void 862 863Reads data from a file. This API uses an asynchronous callback to return the result. 864 865**System capability**: SystemCapability.FileManagement.File.FileIO 866 867**Parameters** 868 869 | Name | Type | Mandatory | Description | 870 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 871 | fd | number | Yes | FD of the file. | 872 | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | 873 | options | Object | 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.| 874 | callback | AsyncCallback<number> | Yes | Callback invoked when the data is read asynchronously. | 875 876**Error codes** 877 878For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 879 880**Example** 881 882 ```ts 883 import { BusinessError } from '@ohos.base'; 884 import buffer from '@ohos.buffer'; 885 let filePath = pathDir + "/test.txt"; 886 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 887 let arrayBuffer = new ArrayBuffer(4096); 888 fs.read(file.fd, arrayBuffer, (err: BusinessError, readLen: number) => { 889 if (err) { 890 console.info("read failed with error message: " + err.message + ", error code: " + err.code); 891 } else { 892 console.info("Read file data successfully"); 893 let buf = buffer.from(arrayBuffer, 0, readLen); 894 console.info(`The content of file: ${buf.toString()}`); 895 } 896 fs.closeSync(file); 897 }); 898 ``` 899 900## fs.readSync 901 902readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number 903 904Reads data from a file. This API returns the result synchronously. 905 906**System capability**: SystemCapability.FileManagement.File.FileIO 907 908**Parameters** 909 910 | Name | Type | Mandatory | Description | 911 | ------- | ----------- | ---- | ---------------------------------------- | 912 | fd | number | Yes | FD of the file. | 913 | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | 914 | options | Object | 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.| 915 916**Return value** 917 918 | Type | Description | 919 | ------ | -------- | 920 | number | Length of the data read.| 921 922**Error codes** 923 924For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 925 926**Example** 927 928 ```ts 929 let filePath = pathDir + "/test.txt"; 930 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 931 let buf = new ArrayBuffer(4096); 932 fs.readSync(file.fd, buf); 933 fs.closeSync(file); 934 ``` 935 936## fs.rmdir 937 938rmdir(path: string): Promise<void> 939 940Deletes a directory. This API uses a promise to return the result. 941 942**System capability**: SystemCapability.FileManagement.File.FileIO 943 944**Parameters** 945 946| Name| Type | Mandatory| Description | 947| ------ | ------ | ---- | -------------------------- | 948| path | string | Yes | Application sandbox path of the directory.| 949 950**Return value** 951 952 | Type | Description | 953 | ------------------- | ---------------------------- | 954 | Promise<void> | Promise that returns no value.| 955 956**Error codes** 957 958For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 959 960**Example** 961 962 ```ts 963 import { BusinessError } from '@ohos.base'; 964 let dirPath = pathDir + "/testDir"; 965 fs.rmdir(dirPath).then(() => { 966 console.info("Directory deleted"); 967 }).catch((err: BusinessError) => { 968 console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code); 969 }); 970 ``` 971 972## fs.rmdir 973 974rmdir(path: string, callback: AsyncCallback<void>): void 975 976Deletes a directory. This API uses an asynchronous callback to return the result. 977 978**System capability**: SystemCapability.FileManagement.File.FileIO 979 980**Parameters** 981 982| Name | Type | Mandatory| Description | 983| -------- | ------------------------- | ---- | -------------------------- | 984| path | string | Yes | Application sandbox path of the directory.| 985| callback | AsyncCallback<void> | Yes | Callback invoked when the directory is deleted asynchronously. | 986 987**Error codes** 988 989For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 990 991**Example** 992 993 ```ts 994 import { BusinessError } from '@ohos.base'; 995 let dirPath = pathDir + "/testDir"; 996 fs.rmdir(dirPath, (err: BusinessError) => { 997 if (err) { 998 console.info("rmdir failed with error message: " + err.message + ", error code: " + err.code); 999 } else { 1000 console.info("Directory deleted"); 1001 } 1002 }); 1003 ``` 1004 1005## fs.rmdirSync 1006 1007rmdirSync(path: string): void 1008 1009Deletes a directory. This API returns the result synchronously. 1010 1011**System capability**: SystemCapability.FileManagement.File.FileIO 1012 1013**Parameters** 1014 1015| Name| Type | Mandatory| Description | 1016| ------ | ------ | ---- | -------------------------- | 1017| path | string | Yes | Application sandbox path of the directory.| 1018 1019**Error codes** 1020 1021For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1022 1023**Example** 1024 1025 ```ts 1026 let dirPath = pathDir + "/testDir"; 1027 fs.rmdirSync(dirPath); 1028 ``` 1029 1030## fs.unlink 1031 1032unlink(path: string): Promise<void> 1033 1034Deletes a file. This API uses a promise to return the result. 1035 1036**System capability**: SystemCapability.FileManagement.File.FileIO 1037 1038**Parameters** 1039 1040| Name| Type | Mandatory| Description | 1041| ------ | ------ | ---- | -------------------------- | 1042| path | string | Yes | Application sandbox path of the file.| 1043 1044**Return value** 1045 1046 | Type | Description | 1047 | ------------------- | ---------------------------- | 1048 | Promise<void> | Promise that returns no value.| 1049 1050**Error codes** 1051 1052For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1053 1054**Example** 1055 1056 ```ts 1057 import { BusinessError } from '@ohos.base'; 1058 let filePath = pathDir + "/test.txt"; 1059 fs.unlink(filePath).then(() => { 1060 console.info("File deleted"); 1061 }).catch((err: BusinessError) => { 1062 console.info("remove file failed with error message: " + err.message + ", error code: " + err.codeor); 1063 }); 1064 ``` 1065 1066## fs.unlink 1067 1068unlink(path: string, callback: AsyncCallback<void>): void 1069 1070Deletes a file. This API uses an asynchronous callback to return the result. 1071 1072**System capability**: SystemCapability.FileManagement.File.FileIO 1073 1074**Parameters** 1075 1076| Name | Type | Mandatory| Description | 1077| -------- | ------------------------- | ---- | -------------------------- | 1078| path | string | Yes | Application sandbox path of the file.| 1079| callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is deleted. | 1080 1081**Error codes** 1082 1083For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1084 1085**Example** 1086 1087 ```ts 1088 import { BusinessError } from '@ohos.base'; 1089 let filePath = pathDir + "/test.txt"; 1090 fs.unlink(filePath, (err: BusinessError) => { 1091 if (err) { 1092 console.info("remove file failed with error message: " + err.message + ", error code: " + err.code); 1093 } else { 1094 console.info("File deleted"); 1095 } 1096 }); 1097 ``` 1098 1099## fs.unlinkSync 1100 1101unlinkSync(path: string): void 1102 1103Deletes a file. This API returns the result synchronously. 1104 1105**System capability**: SystemCapability.FileManagement.File.FileIO 1106 1107**Parameters** 1108 1109| Name| Type | Mandatory| Description | 1110| ------ | ------ | ---- | -------------------------- | 1111| path | string | Yes | Application sandbox path of the file.| 1112 1113**Error codes** 1114 1115For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1116 1117**Example** 1118 1119 ```ts 1120 let filePath = pathDir + "/test.txt"; 1121 fs.unlinkSync(filePath); 1122 ``` 1123 1124 1125## fs.write 1126 1127write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<number> 1128 1129Writes data into a file. This API uses a promise to return the result. 1130 1131**System capability**: SystemCapability.FileManagement.File.FileIO 1132 1133**Parameters** 1134 1135 | Name | Type | Mandatory | Description | 1136 | ------- | ------------------------------- | ---- | ---------------------------------------- | 1137 | fd | number | Yes | FD of the file. | 1138 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 1139 | options | Object | 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.| 1140 1141**Return value** 1142 1143 | Type | Description | 1144 | --------------------- | -------- | 1145 | Promise<number> | Promise used to return the length of the data written.| 1146 1147**Error codes** 1148 1149For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1150 1151**Example** 1152 1153 ```ts 1154 import { BusinessError } from '@ohos.base'; 1155 let filePath = pathDir + "/test.txt"; 1156 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1157 let str: string = "hello, world"; 1158 fs.write(file.fd, str).then((writeLen: number) => { 1159 console.info("write data to file succeed and size is:" + writeLen); 1160 }).catch((err: BusinessError) => { 1161 console.info("write data to file failed with error message: " + err.message + ", error code: " + err.code); 1162 }).finally(() => { 1163 fs.closeSync(file); 1164 }); 1165 ``` 1166 1167## fs.write 1168 1169write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<number>): void 1170 1171Writes data into a file. This API uses an asynchronous callback to return the result. 1172 1173**System capability**: SystemCapability.FileManagement.File.FileIO 1174 1175**Parameters** 1176 1177 | Name | Type | Mandatory | Description | 1178 | -------- | ------------------------------- | ---- | ---------------------------------------- | 1179 | fd | number | Yes | FD of the file. | 1180 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 1181 | options | Object | 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.| 1182 | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | 1183 1184**Error codes** 1185 1186For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1187 1188**Example** 1189 1190 ```ts 1191 import { BusinessError } from '@ohos.base'; 1192 let filePath = pathDir + "/test.txt"; 1193 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1194 let str: string = "hello, world"; 1195 fs.write(file.fd, str, (err: BusinessError, writeLen: number) => { 1196 if (err) { 1197 console.info("write failed with error message: " + err.message + ", error code: " + err.code); 1198 } else { 1199 console.info("write data to file succeed and size is:" + writeLen); 1200 } 1201 fs.closeSync(file); 1202 }); 1203 ``` 1204 1205## fs.writeSync 1206 1207writeSync(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number 1208 1209Writes data into a file. This API returns the result synchronously. 1210 1211**System capability**: SystemCapability.FileManagement.File.FileIO 1212 1213**Parameters** 1214 1215 | Name | Type | Mandatory | Description | 1216 | ------- | ------------------------------- | ---- | ---------------------------------------- | 1217 | fd | number | Yes | FD of the file. | 1218 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 1219 | options | Object | 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.| 1220 1221**Return value** 1222 1223 | Type | Description | 1224 | ------ | -------- | 1225 | number | Length of the data written in the file.| 1226 1227**Error codes** 1228 1229For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1230 1231**Example** 1232 1233 ```ts 1234 let filePath = pathDir + "/test.txt"; 1235 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 1236 let str: string = "hello, world"; 1237 let writeLen = fs.writeSync(file.fd, str); 1238 console.info("write data to file succeed and size is:" + writeLen); 1239 fs.closeSync(file); 1240 ``` 1241 1242## fs.truncate 1243 1244truncate(file: string|number, len?: number): Promise<void> 1245 1246Truncates a file. This API uses a promise to return the result. 1247 1248**System capability**: SystemCapability.FileManagement.File.FileIO 1249 1250**Parameters** 1251 1252| Name| Type | Mandatory| Description | 1253| ------ | ------ | ---- | -------------------------------- | 1254| file | string\|number | Yes | Application sandbox path or FD of the file. | 1255| len | number | No | File length, in bytes, after truncation. The default value is **0**.| 1256 1257**Return value** 1258 1259 | Type | Description | 1260 | ------------------- | ---------------------------- | 1261 | Promise<void> | Promise that returns no value.| 1262 1263**Error codes** 1264 1265For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1266 1267**Example** 1268 1269 ```ts 1270 import { BusinessError } from '@ohos.base'; 1271 let filePath = pathDir + "/test.txt"; 1272 let len: number = 5; 1273 fs.truncate(filePath, len).then(() => { 1274 console.info("File truncated"); 1275 }).catch((err: BusinessError) => { 1276 console.info("truncate file failed with error message: " + err.message + ", error code: " + err.code); 1277 }); 1278 ``` 1279 1280## fs.truncate 1281 1282truncate(file: string|number, len?: number, callback: AsyncCallback<void>): void 1283 1284Truncates a file. This API uses an asynchronous callback to return the result. 1285 1286**System capability**: SystemCapability.FileManagement.File.FileIO 1287 1288**Parameters** 1289 1290| Name | Type | Mandatory| Description | 1291| -------- | ------------------------- | ---- | -------------------------------- | 1292| file | string\|number | Yes | Application sandbox path or FD of the file. | 1293| len | number | No | File length, in bytes, after truncation. The default value is **0**.| 1294| callback | AsyncCallback<void> | Yes | Callback that returns no value. | 1295 1296**Error codes** 1297 1298For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1299 1300**Example** 1301 1302 ```ts 1303 import { BusinessError } from '@ohos.base'; 1304 let filePath = pathDir + "/test.txt"; 1305 let len: number = 5; 1306 fs.truncate(filePath, len, (err: BusinessError) => { 1307 if (err) { 1308 console.info("truncate failed with error message: " + err.message + ", error code: " + err.code); 1309 } else { 1310 console.info("truncate success"); 1311 } 1312 }); 1313 ``` 1314 1315## fs.truncateSync 1316 1317truncateSync(file: string|number, len?: number): void 1318 1319Truncates a file. This API returns the result synchronously. 1320 1321**System capability**: SystemCapability.FileManagement.File.FileIO 1322 1323**Parameters** 1324 1325| Name| Type | Mandatory| Description | 1326| ------ | ------ | ---- | -------------------------------- | 1327| file | string\|number | Yes | Application sandbox path or FD of the file. | 1328| len | number | No | File length, in bytes, after truncation. The default value is **0**.| 1329 1330**Error codes** 1331 1332For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1333 1334**Example** 1335 1336 ```ts 1337 let filePath = pathDir + "/test.txt"; 1338 let len: number = 5; 1339 fs.truncateSync(filePath, len); 1340 ``` 1341 1342## fs.readText 1343 1344readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<string> 1345 1346Reads the text content of a file. This API uses a promise to return the result. 1347 1348**System capability**: SystemCapability.FileManagement.File.FileIO 1349 1350**Parameters** 1351 1352| Name | Type | Mandatory| Description | 1353| -------- | ------ | ---- | ------------------------------------------------------------ | 1354| filePath | string | Yes | Application sandbox path of the file. | 1355| options | Object | 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 (string) to be encoded. The default value is **'utf-8'**, which is the only value supported.| 1356 1357**Return value** 1358 1359 | Type | Description | 1360 | --------------------- | ---------- | 1361 | Promise<string> | Promise used to return the file content read.| 1362 1363**Error codes** 1364 1365For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1366 1367**Example** 1368 1369 ```ts 1370 import { BusinessError } from '@ohos.base'; 1371 let filePath = pathDir + "/test.txt"; 1372 fs.readText(filePath).then((str: string) => { 1373 console.info("readText succeed:" + str); 1374 }).catch((err: BusinessError) => { 1375 console.info("readText failed with error message: " + err.message + ", error code: " + err.code); 1376 }); 1377 ``` 1378 1379## fs.readText 1380 1381readText(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<string>): void 1382 1383Reads the text content of a file. This API uses an asynchronous callback to return the result. 1384 1385**System capability**: SystemCapability.FileManagement.File.FileIO 1386 1387**Parameters** 1388 1389| Name | Type | Mandatory| Description | 1390| -------- | --------------------------- | ---- | ------------------------------------------------------------ | 1391| filePath | string | Yes | Application sandbox path of the file. | 1392| options | Object | 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.| 1393| callback | AsyncCallback<string> | Yes | Callback invoked to return the content read. | 1394 1395**Error codes** 1396 1397For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1398 1399**Example** 1400 1401 ```ts 1402 import { BusinessError } from '@ohos.base'; 1403 let filePath = pathDir + "/test.txt"; 1404 class Option { 1405 offset: number = 0; 1406 length: number = 0; 1407 encoding: string = 'utf-8'; 1408 } 1409 let stat = fs.statSync(filePath); 1410 let option = new Option(); 1411 option.offset = 1; 1412 option.length = stat.size; 1413 fs.readText(filePath, option, (err: BusinessError, str: string) => { 1414 if (err) { 1415 console.info("read text failed with error message: " + err.message + ", error code: " + err.code); 1416 } else { 1417 console.info("readText succeed:" + str); 1418 } 1419 }); 1420 ``` 1421 1422## fs.readTextSync 1423 1424readTextSync(filePath: string, options?: { offset?: number; length?: number; encoding?: string; }): string 1425 1426Reads the text of a file. This API returns the result synchronously. 1427 1428**System capability**: SystemCapability.FileManagement.File.FileIO 1429 1430**Parameters** 1431 1432| Name | Type | Mandatory| Description | 1433| -------- | ------ | ---- | ------------------------------------------------------------ | 1434| filePath | string | Yes | Application sandbox path of the file. | 1435| options | Object | 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 (string) to be encoded. The default value is **'utf-8'**, which is the only value supported.| 1436 1437**Return value** 1438 1439 | Type | Description | 1440 | ------ | -------------------- | 1441 | string | Returns the content of the file read.| 1442 1443**Error codes** 1444 1445For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1446 1447**Example** 1448 1449 ```ts 1450 let filePath = pathDir + "/test.txt"; 1451 class Option { 1452 offset: number = 0; 1453 length: number = 0; 1454 encoding: string = 'utf-8'; 1455 } 1456 let stat = fs.statSync(filePath); 1457 let option = new Option(); 1458 option.offset = 1; 1459 option.length = stat.size; 1460 let str = fs.readTextSync(filePath, option); 1461 console.info("readText succeed:" + str); 1462 ``` 1463 1464## fs.lstat 1465 1466lstat(path: string): Promise<Stat> 1467 1468Obtains information about a symbolic link. This API uses a promise to return the result. 1469 1470**System capability**: SystemCapability.FileManagement.File.FileIO 1471 1472**Parameters** 1473 1474| Name| Type | Mandatory| Description | 1475| ------ | ------ | ---- | -------------------------------------- | 1476| path | string | Yes | Application sandbox path of the file.| 1477 1478**Return value** 1479 1480 | Type | Description | 1481 | ---------------------------- | ---------- | 1482 | Promise<[Stat](#stat)> | Promise used to return the symbolic link information obtained. For details, see **stat**.| 1483 1484**Error codes** 1485 1486For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1487 1488**Example** 1489 1490 ```ts 1491 import { BusinessError } from '@ohos.base'; 1492 let filePath = pathDir + "/test.txt"; 1493 fs.lstat(filePath).then((stat: fs.Stat) => { 1494 console.info("get link status succeed, the size of file is" + stat.size); 1495 }).catch((err: BusinessError) => { 1496 console.info("get link status failed with error message: " + err.message + ", error code: " + err.code); 1497 }); 1498 ``` 1499 1500## fs.lstat 1501 1502lstat(path: string, callback: AsyncCallback<Stat>): void 1503 1504Obtains information about a symbolic link. This API uses an asynchronous callback to return the result. 1505 1506**System capability**: SystemCapability.FileManagement.File.FileIO 1507 1508**Parameters** 1509 1510| Name | Type | Mandatory| Description | 1511| -------- | ---------------------------------- | ---- | -------------------------------------- | 1512| path | string | Yes | Application sandbox path of the file.| 1513| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the symbolic link information obtained. | 1514 1515**Error codes** 1516 1517For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1518 1519**Example** 1520 1521 ```ts 1522 import { BusinessError } from '@ohos.base'; 1523 let filePath = pathDir + "/test.txt"; 1524 fs.lstat(filePath, (err: BusinessError, stat: fs.Stat) => { 1525 if (err) { 1526 console.info("lstat failed with error message: " + err.message + ", error code: " + err.code); 1527 } else { 1528 console.info("get link status succeed, the size of file is" + stat.size); 1529 } 1530 }); 1531 ``` 1532 1533## fs.lstatSync 1534 1535lstatSync(path: string): Stat 1536 1537Obtains information about a symbolic link synchronously. 1538 1539**System capability**: SystemCapability.FileManagement.File.FileIO 1540 1541**Parameters** 1542 1543| Name| Type | Mandatory| Description | 1544| ------ | ------ | ---- | -------------------------------------- | 1545| path | string | Yes | Application sandbox path of the file.| 1546 1547**Return value** 1548 1549 | Type | Description | 1550 | ------------- | ---------- | 1551 | [Stat](#stat) | File information obtained.| 1552 1553**Error codes** 1554 1555For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1556 1557**Example** 1558 1559 ```ts 1560 let filePath = pathDir + "/test.txt"; 1561 fs.lstatSync(filePath); 1562 ``` 1563 1564## fs.rename 1565 1566rename(oldPath: string, newPath: string): Promise<void> 1567 1568Renames a file or folder. This API uses a promise to return the result. 1569 1570**System capability**: SystemCapability.FileManagement.File.FileIO 1571 1572**Parameters** 1573 1574| Name | Type | Mandatory| Description | 1575| ------- | ------ | ---- | ---------------------------- | 1576| oldPath | string | Yes | Application sandbox path of the file to rename.| 1577| newPath | string | Yes | Application sandbox path of the renamed file. | 1578 1579**Return value** 1580 1581 | Type | Description | 1582 | ------------------- | ---------------------------- | 1583 | Promise<void> | Promise that returns no value.| 1584 1585**Error codes** 1586 1587For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1588 1589**Example** 1590 1591 ```ts 1592 import { BusinessError } from '@ohos.base'; 1593 let srcFile = pathDir + "/test.txt"; 1594 let dstFile = pathDir + "/new.txt"; 1595 fs.rename(srcFile, dstFile).then(() => { 1596 console.info("File renamed"); 1597 }).catch((err: BusinessError) => { 1598 console.info("rename failed with error message: " + err.message + ", error code: " + err.code); 1599 }); 1600 ``` 1601 1602## fs.rename 1603 1604rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): void 1605 1606Renames a file or folder. This API uses an asynchronous callback to return the result. 1607 1608**System capability**: SystemCapability.FileManagement.File.FileIO 1609 1610**Parameters** 1611 1612| Name | Type | Mandatory| Description | 1613| -------- | ------------------------- | ---- | ---------------------------- | 1614| oldPath | string | Yes | Application sandbox path of the file to rename.| 1615| newPath | string | Yes | Application sandbox path of the renamed file. | 1616| callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | 1617 1618**Error codes** 1619 1620For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1621 1622**Example** 1623 1624 ```ts 1625 import { BusinessError } from '@ohos.base'; 1626 let srcFile = pathDir + "/test.txt"; 1627 let dstFile = pathDir + "/new.txt"; 1628 fs.rename(srcFile, dstFile, (err: BusinessError) => { 1629 if (err) { 1630 console.info("rename failed with error message: " + err.message + ", error code: " + err.code); 1631 } else { 1632 console.info("rename success"); 1633 } 1634 }); 1635 ``` 1636 1637## fs.renameSync 1638 1639renameSync(oldPath: string, newPath: string): void 1640 1641Renames a file or folder synchronously. 1642 1643**System capability**: SystemCapability.FileManagement.File.FileIO 1644 1645**Parameters** 1646 1647| Name | Type | Mandatory| Description | 1648| ------- | ------ | ---- | ---------------------------- | 1649| oldPath | string | Yes | Application sandbox path of the file to rename.| 1650| newPath | string | Yes | Application sandbox path of the renamed file. | 1651 1652**Error codes** 1653 1654For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1655 1656**Example** 1657 1658 ```ts 1659 let srcFile = pathDir + "/test.txt"; 1660 let dstFile = pathDir + "/new.txt"; 1661 fs.renameSync(srcFile, dstFile); 1662 ``` 1663 1664## fs.fsync 1665 1666fsync(fd: number): Promise<void> 1667 1668Flushes data of a file to disk. This API uses a promise to return the result. 1669 1670**System capability**: SystemCapability.FileManagement.File.FileIO 1671 1672**Parameters** 1673 1674 | Name | Type | Mandatory | Description | 1675 | ---- | ------ | ---- | ------------ | 1676 | fd | number | Yes | FD of the file.| 1677 1678**Return value** 1679 1680 | Type | Description | 1681 | ------------------- | ---------------------------- | 1682 | Promise<void> | Promise that returns no value.| 1683 1684**Error codes** 1685 1686For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1687 1688**Example** 1689 1690 ```ts 1691 import { BusinessError } from '@ohos.base'; 1692 let filePath = pathDir + "/test.txt"; 1693 let file = fs.openSync(filePath); 1694 fs.fsync(file.fd).then(() => { 1695 console.info("Data flushed"); 1696 }).catch((err: BusinessError) => { 1697 console.info("sync data failed with error message: " + err.message + ", error code: " + err.code); 1698 }).finally(() => { 1699 fs.closeSync(file); 1700 }); 1701 ``` 1702 1703## fs.fsync 1704 1705fsync(fd: number, callback: AsyncCallback<void>): void 1706 1707Flushes data of a file to disk. This API uses an asynchronous callback to return the result. 1708 1709**System capability**: SystemCapability.FileManagement.File.FileIO 1710 1711**Parameters** 1712 1713 | Name | Type | Mandatory | Description | 1714 | -------- | ------------------------- | ---- | --------------- | 1715 | fd | number | Yes | FD of the file. | 1716 | Callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| 1717 1718**Error codes** 1719 1720For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1721 1722**Example** 1723 1724 ```ts 1725 import { BusinessError } from '@ohos.base'; 1726 let filePath = pathDir + "/test.txt"; 1727 let file = fs.openSync(filePath); 1728 fs.fsync(file.fd, (err: BusinessError) => { 1729 if (err) { 1730 console.info("fsync failed with error message: " + err.message + ", error code: " + err.code); 1731 } else { 1732 console.info("fsync success"); 1733 } 1734 fs.closeSync(file); 1735 }); 1736 ``` 1737 1738 1739## fs.fsyncSync 1740 1741fsyncSync(fd: number): void 1742 1743Flushes data of a file to disk synchronously. 1744 1745**System capability**: SystemCapability.FileManagement.File.FileIO 1746 1747**Parameters** 1748 1749 | Name | Type | Mandatory | Description | 1750 | ---- | ------ | ---- | ------------ | 1751 | fd | number | Yes | FD of the file.| 1752 1753**Error codes** 1754 1755For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1756 1757**Example** 1758 1759 ```ts 1760 let filePath = pathDir + "/test.txt"; 1761 let file = fs.openSync(filePath); 1762 fs.fsyncSync(file.fd); 1763 fs.closeSync(file); 1764 ``` 1765 1766## fs.fdatasync 1767 1768fdatasync(fd: number): Promise<void> 1769 1770Flushes data of a file to disk. 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. 1771 1772**System capability**: SystemCapability.FileManagement.File.FileIO 1773 1774**Parameters** 1775 1776 | Name | Type | Mandatory | Description | 1777 | ---- | ------ | ---- | ------------ | 1778 | fd | number | Yes | FD of the file.| 1779 1780**Return value** 1781 1782 | Type | Description | 1783 | ------------------- | ---------------------------- | 1784 | Promise<void> | Promise that returns no value.| 1785 1786**Error codes** 1787 1788For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1789 1790**Example** 1791 1792 ```ts 1793 import { BusinessError } from '@ohos.base'; 1794 let filePath = pathDir + "/test.txt"; 1795 let file = fs.openSync(filePath); 1796 fs.fdatasync(file.fd).then((err: BusinessError) => { 1797 console.info("Data flushed"); 1798 }).catch((err: BusinessError) => { 1799 console.info("sync data failed with error message: " + err.message + ", error code: " + err.code); 1800 }).finally(() => { 1801 fs.closeSync(file); 1802 }); 1803 ``` 1804 1805## fs.fdatasync 1806 1807fdatasync(fd: number, callback: AsyncCallback<void>): void 1808 1809Flushes data of a file to disk. This API uses an asynchronous callback to return the result. 1810 1811**System capability**: SystemCapability.FileManagement.File.FileIO 1812 1813**Parameters** 1814 1815 | Name | Type | Mandatory | Description | 1816 | -------- | ------------------------------- | ---- | ----------------- | 1817 | fd | number | Yes | FD of the file. | 1818 | callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| 1819 1820**Error codes** 1821 1822For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1823 1824**Example** 1825 1826 ```ts 1827 import { BusinessError } from '@ohos.base'; 1828 let filePath = pathDir + "/test.txt"; 1829 let file = fs.openSync(filePath); 1830 fs.fdatasync (file.fd, (err: BusinessError) => { 1831 if (err) { 1832 console.info("fdatasync failed with error message: " + err.message + ", error code: " + err.code); 1833 } else { 1834 console.info("fdatasync success"); 1835 } 1836 fs.closeSync(file); 1837 }); 1838 ``` 1839 1840## fs.fdatasyncSync 1841 1842fdatasyncSync(fd: number): void 1843 1844Synchronizes data in a file synchronously. 1845 1846**System capability**: SystemCapability.FileManagement.File.FileIO 1847 1848**Parameters** 1849 1850 | Name | Type | Mandatory | Description | 1851 | ---- | ------ | ---- | ------------ | 1852 | fd | number | Yes | FD of the file.| 1853 1854**Error codes** 1855 1856For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1857 1858**Example** 1859 1860 ```ts 1861 let filePath = pathDir + "/test.txt"; 1862 let file = fs.openSync(filePath); 1863 let stat = fs.fdatasyncSync(file.fd); 1864 fs.closeSync(file); 1865 ``` 1866 1867## fs.symlink 1868 1869symlink(target: string, srcPath: string): Promise<void> 1870 1871Creates a symbolic link based on a file path. This API uses a promise to return the result. 1872 1873**System capability**: SystemCapability.FileManagement.File.FileIO 1874 1875**Parameters** 1876 1877| Name | Type | Mandatory| Description | 1878| ------- | ------ | ---- | ---------------------------- | 1879| target | string | Yes | Application sandbox path of the source file. | 1880| srcPath | string | Yes | Application sandbox path of the symbolic link.| 1881 1882**Return value** 1883 1884 | Type | Description | 1885 | ------------------- | ---------------------------- | 1886 | Promise<void> | Promise that returns no value.| 1887 1888**Error codes** 1889 1890For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1891 1892**Example** 1893 1894 ```ts 1895 import { BusinessError } from '@ohos.base'; 1896 let srcFile = pathDir + "/test.txt"; 1897 let dstFile = pathDir + "/test"; 1898 fs.symlink(srcFile, dstFile).then(() => { 1899 console.info("Symbolic link created"); 1900 }).catch((err: BusinessError) => { 1901 console.info("symlink failed with error message: " + err.message + ", error code: " + err.code); 1902 }); 1903 ``` 1904 1905 1906## fs.symlink 1907symlink(target: string, srcPath: string, callback: AsyncCallback<void>): void 1908 1909Creates a symbolic link based on a file path. This API uses an asynchronous callback to return the result. 1910 1911**System capability**: SystemCapability.FileManagement.File.FileIO 1912 1913**Parameters** 1914 1915| Name | Type | Mandatory| Description | 1916| -------- | ------------------------- | ---- | -------------------------------- | 1917| target | string | Yes | Application sandbox path of the source file. | 1918| srcPath | string | Yes | Application sandbox path of the symbolic link. | 1919| callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| 1920 1921**Error codes** 1922 1923For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1924 1925**Example** 1926 1927 ```ts 1928 import { BusinessError } from '@ohos.base'; 1929 let srcFile = pathDir + "/test.txt"; 1930 let dstFile = pathDir + "/test"; 1931 fs.symlink(srcFile, dstFile, (err: BusinessError) => { 1932 if (err) { 1933 console.info("symlink failed with error message: " + err.message + ", error code: " + err.code); 1934 } else { 1935 console.info("symlink success"); 1936 } 1937 }); 1938 ``` 1939 1940## fs.symlinkSync 1941 1942symlinkSync(target: string, srcPath: string): void 1943 1944Creates a symbolic link based on a file path. This API returns the result synchronously. 1945 1946**System capability**: SystemCapability.FileManagement.File.FileIO 1947 1948**Parameters** 1949 1950| Name | Type | Mandatory| Description | 1951| ------- | ------ | ---- | ---------------------------- | 1952| target | string | Yes | Application sandbox path of the source file. | 1953| srcPath | string | Yes | Application sandbox path of the symbolic link.| 1954 1955**Error codes** 1956 1957For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 1958 1959**Example** 1960 1961 ```ts 1962 let srcFile = pathDir + "/test.txt"; 1963 let dstFile = pathDir + "/test"; 1964 fs.symlinkSync(srcFile, dstFile); 1965 ``` 1966 1967## fs.listFile 1968listFile(path: string, options?: { 1969 recursion?: boolean; 1970 listNum?: number; 1971 filter?: Filter; 1972}): Promise<string[]> 1973 1974Lists all files in a folder. This API uses a promise to return the result.<br>This API supports recursive listing of all files (including files in subfolders) and file filtering. 1975 1976**System capability**: SystemCapability.FileManagement.File.FileIO 1977 1978**Parameters** 1979 1980 | Name | Type | Mandatory | Description | 1981 | ------ | ------ | ---- | --------------------------- | 1982 | path | string | Yes | Application sandbox path of the folder.| 1983 | options | Object | No | File filtering options. The files are not filtered by default.| 1984 1985**options parameters** 1986 1987 | Name | Type | Mandatory | Description | 1988 | ------ | ------ | ---- | --------------------------- | 1989 | recursion | boolean | No | Whether to list all files in subfolders recursively. 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**, the relative paths (starting with /) of all files that meet the specified conditions in the directory are returned.| 1990 | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| 1991 | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| 1992 1993**Return value** 1994 1995 | Type | Description | 1996 | --------------------- | ---------- | 1997 | Promise<string[]> | Promise used to return the file names listed.| 1998 1999**Error codes** 2000 2001For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2002 2003**Example** 2004 2005 ```ts 2006 import { BusinessError } from '@ohos.base'; 2007 import fs, { Filter } from '@ohos.file.fs'; 2008 class ListFileOption { 2009 public recursion: boolean = false; 2010 public listNum: number = 0; 2011 public filter: Filter; 2012 } 2013 let option = new ListFileOption(); 2014 option.filter.suffix = [".png", ".jpg", ".jpeg"]; 2015 option.filter.displayName = ["*abc", "efg*"]; 2016 option.filter.fileSizeOver = 1024; 2017 option.filter.lastModifiedAfter = new Date().getTime(); 2018 fs.listFile(pathDir, option).then((filenames: Array<string>) => { 2019 console.info("listFile succeed"); 2020 for (let i = 0; i < filenames.length; i++) { 2021 console.info("fileName: %s", filenames[i]); 2022 } 2023 }).catch((err: BusinessError) => { 2024 console.info("list file failed with error message: " + err.message + ", error code: " + err.code); 2025 }); 2026 ``` 2027 2028## fs.listFile 2029listFile(path: string, options?: { 2030 recursion?: boolean; 2031 listNum?: number; 2032 filter?: Filter; 2033}, callback: AsyncCallback<string[]>): void 2034 2035Lists all files in a folder. This API uses an asynchronous callback to return the result.<br>This API supports recursive listing of all files (including files in subfolders) and file filtering. 2036 2037**System capability**: SystemCapability.FileManagement.File.FileIO 2038 2039**Parameters** 2040 2041 | Name | Type | Mandatory | Description | 2042 | ------ | ------ | ---- | --------------------------- | 2043 | path | string | Yes | Application sandbox path of the folder.| 2044 | options | Object | No | File filtering options. The files are not filtered by default.| 2045 | callback | AsyncCallback<string[]> | Yes | Callback invoked to return the file names listed. | 2046 2047**options parameters** 2048 2049 | Name | Type | Mandatory | Description | 2050 | ------ | ------ | ---- | --------------------------- | 2051 | recursion | boolean | No | Whether to list all files in subfolders recursively. 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**, the relative paths (starting with /) of all files that meet the specified conditions in the directory are returned.| 2052 | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| 2053 | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| 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 import fs, { Filter } from '@ohos.file.fs'; 2064 class ListFileOption { 2065 public recursion: boolean = false; 2066 public listNum: number = 0; 2067 public filter: Filter; 2068 } 2069 let option = new ListFileOption(); 2070 option.filter.suffix = [".png", ".jpg", ".jpeg"]; 2071 option.filter.displayName = ["*abc", "efg*"]; 2072 option.filter.fileSizeOver = 1024; 2073 option.filter.lastModifiedAfter = new Date().getTime(); 2074 fs.listFile(pathDir, option, (err: BusinessError, filenames: Array<string>) => { 2075 if (err) { 2076 console.info("list file failed with error message: " + err.message + ", error code: " + err.code); 2077 } else { 2078 console.info("listFile succeed"); 2079 for (let i = 0; i < filenames.length; i++) { 2080 console.info("filename: %s", filenames[i]); 2081 } 2082 } 2083 }); 2084 ``` 2085 2086## fs.listFileSync 2087 2088listFileSync(path: string, options?: { 2089 recursion?: boolean; 2090 listNum?: number; 2091 filter?: Filter; 2092}): string[] 2093 2094Lists all files in a folder synchronously. This API supports recursive listing of all files (including files in subfolders) and file filtering. 2095 2096**System capability**: SystemCapability.FileManagement.File.FileIO 2097 2098**Parameters** 2099 2100 | Name | Type | Mandatory | Description | 2101 | ------ | ------ | ---- | --------------------------- | 2102 | path | string | Yes | Application sandbox path of the folder.| 2103 | options | Object | No | File filtering options. The files are not filtered by default.| 2104 2105**options parameters** 2106 2107 | Name | Type | Mandatory | Description | 2108 | ------ | ------ | ---- | --------------------------- | 2109 | recursion | boolean | No | Whether to list all files in subfolders recursively. 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**, the relative paths (starting with /) of all files that meet the specified conditions in the directory are returned.| 2110 | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| 2111 | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| 2112 2113**Return value** 2114 2115 | Type | Description | 2116 | --------------------- | ---------- | 2117 | string[] | File names listed.| 2118 2119**Error codes** 2120 2121For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2122 2123**Example** 2124 2125 ```ts 2126 import fs, { Filter } from '@ohos.file.fs'; 2127 class ListFileOption { 2128 public recursion: boolean = false; 2129 public listNum: number = 0; 2130 public filter: Filter; 2131 } 2132 let option = new ListFileOption(); 2133 option.filter.suffix = [".png", ".jpg", ".jpeg"]; 2134 option.filter.displayName = ["*abc", "efg*"]; 2135 option.filter.fileSizeOver = 1024; 2136 option.filter.lastModifiedAfter = new Date().getTime(); 2137 let filenames = fs.listFileSync(pathDir, option); 2138 console.info("listFile succeed"); 2139 for (let i = 0; i < filenames.length; i++) { 2140 console.info("filename: %s", filenames[i]); 2141 } 2142 ``` 2143 2144## fs.moveDir<sup>10+</sup> 2145 2146moveDir(src: string, dest: string, mode?: number): Promise\<void> 2147 2148Moves a directory. This API uses a promise to return the result. 2149 2150**System capability**: SystemCapability.FileManagement.File.FileIO 2151 2152**Parameters** 2153 2154 | Name | Type | Mandatory | Description | 2155 | ------ | ------ | ---- | --------------------------- | 2156 | src | string | Yes | Application sandbox path of the directory to move.| 2157 | dest | string | Yes | Application sandbox path of the destination directory.| 2158 | mode | number | No | Mode for moving the directory. 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 directory 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 directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.<br>- **2**: Forcibly overwrite the conflicting files in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.<br>- **3**: Forcibly overwrite the conflicting directory.<br>Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.| 2159 2160**Return value** 2161 2162 | Type | Description | 2163 | ------------------- | ---------------------------- | 2164 | Promise<void> | Promise that returns no value.| 2165 2166**Error codes** 2167 2168For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2169 2170**Example** 2171 2172 ```ts 2173 import { BusinessError } from '@ohos.base'; 2174 // move directory from srcPath to destPath 2175 let srcPath = pathDir + "/srcDir/"; 2176 let destPath = pathDir + "/destDir/"; 2177 fs.moveDir(srcPath, destPath, 1).then(() => { 2178 console.info("move directory succeed"); 2179 }).catch((err: BusinessError) => { 2180 console.info("move directory failed with error message: " + err.message + ", error code: " + err.code); 2181 }); 2182 ``` 2183 2184## fs.moveDir<sup>10+</sup> 2185 2186moveDir(src: string, dest: string, mode?: number, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void 2187 2188Moves a directory. This API uses an asynchronous callback to return the result. 2189 2190**System capability**: SystemCapability.FileManagement.File.FileIO 2191 2192**Parameters** 2193 2194 | Name | Type | Mandatory | Description | 2195 | ------ | ------ | ---- | --------------------------- | 2196 | src | string | Yes | Application sandbox path of the source directory.| 2197 | dest | string | Yes | Application sandbox path of the destination directory.| 2198 | mode | number | No | Mode for moving the directory. The default value is **0**.<br>- **0**: Throw an exception if a directory conflict occurs.<br>Throw an exception if there is a directory 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 directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.<br>- **2**: Forcibly overwrite the conflicting files in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.<br>- **3**: Forcibly overwrite the conflicting directory.<br>Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.| 2199 | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | Yes | Callback invoked when the directory is moved. | 2200 2201**Error codes** 2202 2203For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2204 2205**Example** 2206 2207 ```ts 2208 import { BusinessError } from '@ohos.base'; 2209 import fs, { ConflictFiles } from '@ohos.file.fs'; 2210 // move directory from srcPath to destPath 2211 let srcPath = pathDir + "/srcDir/"; 2212 let destPath = pathDir + "/destDir/"; 2213 fs.moveDir(srcPath, destPath, 1, (err: BusinessError, data: Array<ConflictFiles>) => { 2214 if (err && err.code == 13900015) { 2215 for (let i = 0; i < data.length; i++) { 2216 console.info("move directory failed with conflicting files: " + data[i].srcFile + " " + data[i].destFile); 2217 } 2218 } else if (err) { 2219 console.info("move directory failed with error message: " + err.message + ", error code: " + err.code); 2220 } else { 2221 console.info("move directory succeed"); 2222 } 2223 }); 2224 ``` 2225 2226## fs.moveDirSync<sup>10+</sup> 2227 2228moveDirSync(src: string, dest: string, mode?: number): void 2229 2230Moves a directory. This API returns the result synchronously. 2231 2232**System capability**: SystemCapability.FileManagement.File.FileIO 2233 2234**Parameters** 2235 2236 | Name | Type | Mandatory | Description | 2237 | ------ | ------ | ---- | --------------------------- | 2238 | src | string | Yes | Application sandbox path of the directory to copy.| 2239 | dest | string | Yes | Application sandbox path of the destination directory.| 2240 | mode | number | No | Mode for moving the directory. The default value is **0**.<br>- **0**: Throw an exception if a directory conflict occurs.<br>Throw an exception if there is a directory 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 directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.<br>- **2**: Forcibly overwrite the conflicting files in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.<br>- **3**: Forcibly overwrite the conflicting directory.<br>Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.| 2241 2242**Error codes** 2243 2244For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2245 2246**Example** 2247 2248 ```ts 2249 import { BusinessError } from '@ohos.base'; 2250 // move directory from srcPath to destPath 2251 let srcPath = pathDir + "/srcDir/"; 2252 let destPath = pathDir + "/destDir/"; 2253 try { 2254 fs.moveDirSync(srcPath, destPath, 1); 2255 console.info("move directory succeed"); 2256 } catch (err) { 2257 let err: BusinessError = error as BusinessError; 2258 console.info("move directory failed with error message: " + err.message + ", error code: " + err.code); 2259 } 2260 ``` 2261 2262## fs.moveFile 2263 2264moveFile(src: string, dest: string, mode?: number): Promise\<void> 2265 2266Moves a file. This API uses a promise to return the result. 2267 2268**System capability**: SystemCapability.FileManagement.File.FileIO 2269 2270**Parameters** 2271 2272 | Name | Type | Mandatory | Description | 2273 | ------ | ------ | ---- | --------------------------- | 2274 | src | string | Yes | Application sandbox path of the source file.| 2275 | dest | string | Yes | Application sandbox path of the destination file.| 2276 | 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**.| 2277 2278**Return value** 2279 2280 | Type | Description | 2281 | ------------------- | ---------------------------- | 2282 | Promise<void> | Promise that returns no value.| 2283 2284**Error codes** 2285 2286For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2287 2288**Example** 2289 2290 ```ts 2291 import { BusinessError } from '@ohos.base'; 2292 let srcPath = pathDir + "/source.txt"; 2293 let destPath = pathDir + "/dest.txt"; 2294 fs.moveFile(srcPath, destPath, 0).then(() => { 2295 console.info("move file succeed"); 2296 }).catch((err: BusinessError) => { 2297 console.info("move file failed with error message: " + err.message + ", error code: " + err.code); 2298 }); 2299 ``` 2300 2301## fs.moveFile 2302 2303moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback\<void>): void 2304 2305Moves a file. This API uses an asynchronous callback to return the result. 2306 2307**System capability**: SystemCapability.FileManagement.File.FileIO 2308 2309**Parameters** 2310 2311 | Name | Type | Mandatory | Description | 2312 | ------ | ------ | ---- | --------------------------- | 2313 | src | string | Yes | Application sandbox path of the source file.| 2314 | dest | string | Yes | Application sandbox path of the destination file.| 2315 | 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**.| 2316 | callback | AsyncCallback<void> | Yes | Callback invoked when the file is moved. | 2317 2318**Error codes** 2319 2320For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2321 2322**Example** 2323 2324 ```ts 2325 import { BusinessError } from '@ohos.base'; 2326 let srcPath = pathDir + "/source.txt"; 2327 let destPath = pathDir + "/dest.txt"; 2328 fs.moveFile(srcPath, destPath, 0, (err: BusinessError) => { 2329 if (err) { 2330 console.info("move file failed with error message: " + err.message + ", error code: " + err.code); 2331 } else { 2332 console.info("move file succeed"); 2333 } 2334 }); 2335 ``` 2336 2337## fs.moveFileSync 2338 2339moveFileSync(src: string, dest: string, mode?: number): void 2340 2341Moves a file synchronously. 2342 2343**System capability**: SystemCapability.FileManagement.File.FileIO 2344 2345**Parameters** 2346 2347 | Name | Type | Mandatory | Description | 2348 | ------ | ------ | ---- | --------------------------- | 2349 | src | string | Yes | Application sandbox path of the source file.| 2350 | dest | string | Yes | Application sandbox path of the destination file.| 2351 | 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**.| 2352 2353**Error codes** 2354 2355For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2356 2357**Example** 2358 2359 ```ts 2360 let srcPath = pathDir + "/source.txt"; 2361 let destPath = pathDir + "/dest.txt"; 2362 fs.moveFileSync(srcPath, destPath, 0); 2363 console.info("move file succeed"); 2364 ``` 2365 2366## fs.mkdtemp 2367 2368mkdtemp(prefix: string): Promise<string> 2369 2370Creates a temporary directory. This API uses a promise to return the result. 2371 2372**System capability**: SystemCapability.FileManagement.File.FileIO 2373 2374**Parameters** 2375 2376 | Name | Type | Mandatory | Description | 2377 | ------ | ------ | ---- | --------------------------- | 2378 | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| 2379 2380**Return value** 2381 2382 | Type | Description | 2383 | --------------------- | ---------- | 2384 | Promise<string> | Promise used to return the directory created.| 2385 2386**Error codes** 2387 2388For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2389 2390**Example** 2391 2392 ```ts 2393 import { BusinessError } from '@ohos.base'; 2394 fs.mkdtemp(pathDir + "/XXXXXX").then((dir: string) => { 2395 console.info("mkdtemp succeed:" + dir); 2396 }).catch((err: BusinessError) => { 2397 console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); 2398 }); 2399 ``` 2400 2401## fs.mkdtemp 2402 2403mkdtemp(prefix: string, callback: AsyncCallback<string>): void 2404 2405Creates a temporary directory. This API uses an asynchronous callback to return the result. 2406 2407**System capability**: SystemCapability.FileManagement.File.FileIO 2408 2409**Parameters** 2410 2411 | Name | Type | Mandatory | Description | 2412 | -------- | --------------------------- | ---- | --------------------------- | 2413 | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| 2414 | callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | 2415 2416**Error codes** 2417 2418For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2419 2420**Example** 2421 2422 ```ts 2423 import { BusinessError } from '@ohos.base'; 2424 fs.mkdtemp(pathDir + "/XXXXXX", (err: BusinessError, res: string) => { 2425 if (err) { 2426 console.info("mkdtemp failed with error message: " + err.message + ", error code: " + err.code); 2427 } else { 2428 console.info("mkdtemp success"); 2429 } 2430 }); 2431 ``` 2432 2433## fs.mkdtempSync 2434 2435mkdtempSync(prefix: string): string 2436 2437Creates a temporary directory. This API returns the result synchronously. 2438 2439**System capability**: SystemCapability.FileManagement.File.FileIO 2440 2441**Parameters** 2442 2443 | Name | Type | Mandatory | Description | 2444 | ------ | ------ | ---- | --------------------------- | 2445 | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| 2446 2447**Return value** 2448 2449 | Type | Description | 2450 | ------ | ---------- | 2451 | string | Unique path generated.| 2452 2453**Error codes** 2454 2455For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2456 2457**Example** 2458 2459 ```ts 2460 let res = fs.mkdtempSync(pathDir + "/XXXXXX"); 2461 ``` 2462 2463 2464## fs.createRandomAccessFile<sup>10+</sup> 2465 2466createRandomAccessFile(file: string|File, mode?: number): Promise<RandomAccessFile> 2467 2468Creates a **RandomAccessFile** instance based on the specified file path or file object. This API uses a promise to return the result. 2469 2470**System capability**: SystemCapability.FileManagement.File.FileIO 2471 2472**Parameters** 2473| Name | Type | Mandatory | Description | 2474| ------------ | ------ | ------ | ------------------------------------------------------------ | 2475| file | string\|[File](#file) | Yes | Application sandbox path of the file or an opened file object.| 2476| mode | number | No | [Option](#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.| 2477 2478**Return value** 2479 2480 | Type | Description | 2481 | --------------------------------- | --------- | 2482 | Promise<[RandomAccessFile](#randomaccessfile)> | Promise used to return the **RandomAccessFile** instance created.| 2483 2484**Error codes** 2485 2486For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2487 2488**Example** 2489 2490 ```ts 2491 import { BusinessError } from '@ohos.base'; 2492 let filePath = pathDir + "/test.txt"; 2493 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 2494 fs.createRandomAccessFile(file).then((randomAccessFile: fs.RandomAccessFile) => { 2495 console.info("randomAccessFile fd: " + randomAccessFile.fd); 2496 randomAccessFile.close(); 2497 }).catch((err: BusinessError) => { 2498 console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 2499 }).finally(() => { 2500 fs.closeSync(file); 2501 }); 2502 ``` 2503 2504 2505## fs.createRandomAccessFile<sup>10+</sup> 2506 2507createRandomAccessFile(file: string|File, mode?: number, callback: AsyncCallback<RandomAccessFile>): void 2508 2509Creates a **RandomAccessFile** instance based on the specified file path or file object. This API uses an asynchronous callback to return the result. 2510 2511**System capability**: SystemCapability.FileManagement.File.FileIO 2512 2513**Parameters** 2514 2515| Name | Type | Mandatory | Description | 2516| ------------ | ------ | ------ | ------------------------------------------------------------ | 2517| file | string\|[File](#file) | Yes | Application sandbox path of the file or an opened file object.| 2518| mode | number | No | [Option](#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.| 2519| callback | AsyncCallback<[RandomAccessFile](#randomaccessfile)> | Yes | Callback invoked to return the **RandomAccessFile** instance created. | 2520 2521**Error codes** 2522 2523For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2524 2525**Example** 2526 ```ts 2527 import { BusinessError } from '@ohos.base'; 2528 let filePath = pathDir + "/test.txt"; 2529 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 2530 fs.createRandomAccessFile(file, (err: BusinessError, randomAccessFile: fs.RandomAccessFile) => { 2531 if (err) { 2532 console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 2533 } else { 2534 console.info("randomAccessFilefile fd: " + randomAccessFile.fd); 2535 randomAccessFile.close(); 2536 } 2537 fs.closeSync(file); 2538 }); 2539 ``` 2540 2541 2542## fs.createRandomAccessFileSync<sup>10+</sup> 2543 2544createRandomAccessFileSync(file: string|File, mode?: number): RandomAccessFile 2545 2546Creates a **RandomAccessFile** instance based on the specified file path or file object. 2547 2548**System capability**: SystemCapability.FileManagement.File.FileIO 2549 2550**Parameters** 2551 2552| Name | Type | Mandatory | Description | 2553| ------------ | ------ | ------ | ------------------------------------------------------------ | 2554| file | string\|[File](#file) | Yes | Application sandbox path of the file or an opened file object.| 2555| mode | number | No | [Option](#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.| 2556 2557**Return value** 2558 2559 | Type | Description | 2560 | ------------------ | --------- | 2561 | [RandomAccessFile](#randomaccessfile) | **RandomAccessFile** instance created.| 2562 2563**Error codes** 2564 2565For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2566 2567**Example** 2568 2569 ```ts 2570 let filePath = pathDir + "/test.txt"; 2571 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 2572 let randomaccessfile = fs.createRandomAccessFileSync(file); 2573 randomaccessfile.close(); 2574 fs.closeSync(file); 2575 ``` 2576 2577## fs.createStream 2578 2579createStream(path: string, mode: string): Promise<Stream> 2580 2581Creates a stream based on the file path. This API uses a promise to return the result. 2582 2583**System capability**: SystemCapability.FileManagement.File.FileIO 2584 2585**Parameters** 2586 2587| Name| Type | Mandatory| Description | 2588| ------ | ------ | ---- | ------------------------------------------------------------ | 2589| path | string | Yes | Application sandbox path of the file. | 2590| 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).| 2591 2592**Return value** 2593 2594 | Type | Description | 2595 | --------------------------------- | --------- | 2596 | Promise<[Stream](#stream)> | Promise used to return the stream opened.| 2597 2598**Error codes** 2599 2600For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2601 2602**Example** 2603 2604 ```ts 2605 import { BusinessError } from '@ohos.base'; 2606 let filePath = pathDir + "/test.txt"; 2607 fs.createStream(filePath, "r+").then((stream: fs.Stream) => { 2608 console.info("Stream created"); 2609 }).catch((err: BusinessError) => { 2610 console.info("createStream failed with error message: " + err.message + ", error code: " + err.code); 2611 }); 2612 ``` 2613 2614 2615## fs.createStream 2616 2617createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void 2618 2619Creates a stream based on the file path. This API uses an asynchronous callback to return the result. 2620 2621**System capability**: SystemCapability.FileManagement.File.FileIO 2622 2623**Parameters** 2624 2625| Name | Type | Mandatory| Description | 2626| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 2627| path | string | Yes | Application sandbox path of the file. | 2628| 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).| 2629| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is created asynchronously. | 2630 2631**Error codes** 2632 2633For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2634 2635**Example** 2636 2637 ```ts 2638 import { BusinessError } from '@ohos.base'; 2639 let filePath = pathDir + "/test.txt"; 2640 fs.createStream(filePath, "r+", (err: BusinessError, stream: fs.Stream) => { 2641 if (err) { 2642 console.info("create stream failed with error message: " + err.message + ", error code: " + err.code); 2643 } else { 2644 console.info("create stream success"); 2645 } 2646 }); 2647 ``` 2648 2649## fs.createStreamSync 2650 2651createStreamSync(path: string, mode: string): Stream 2652 2653Creates a stream based on the file path. This API returns the result synchronously. 2654 2655**System capability**: SystemCapability.FileManagement.File.FileIO 2656 2657**Parameters** 2658 2659| Name| Type | Mandatory| Description | 2660| ------ | ------ | ---- | ------------------------------------------------------------ | 2661| path | string | Yes | Application sandbox path of the file. | 2662| 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).| 2663 2664**Return value** 2665 2666 | Type | Description | 2667 | ------------------ | --------- | 2668 | [Stream](#stream) | Stream opened.| 2669 2670**Error codes** 2671 2672For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2673 2674**Example** 2675 2676 ```ts 2677 let filePath = pathDir + "/test.txt"; 2678 let ss = fs.createStreamSync(filePath, "r+"); 2679 ``` 2680 2681 2682## fs.fdopenStream 2683 2684fdopenStream(fd: number, mode: string): Promise<Stream> 2685 2686Opens a stream based on the file descriptor. This API uses a promise to return the result. 2687 2688**System capability**: SystemCapability.FileManagement.File.FileIO 2689 2690**Parameters** 2691 2692 | Name | Type | Mandatory | Description | 2693 | ---- | ------ | ---- | ---------------------------------------- | 2694 | fd | number | Yes | FD of the file. | 2695 | 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).| 2696 2697**Return value** 2698 2699 | Type | Description | 2700 | --------------------------------- | --------- | 2701 | Promise<[Stream](#stream)> | Promise used to return the stream opened.| 2702 2703**Error codes** 2704 2705For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2706 2707**Example** 2708 2709 ```ts 2710 import { BusinessError } from '@ohos.base'; 2711 let filePath = pathDir + "/test.txt"; 2712 let file = fs.openSync(filePath); 2713 fs.fdopenStream(file.fd, "r+").then((stream: fs.Stream) => { 2714 console.info("Stream opened"); 2715 stream.closeSync(); 2716 }).catch((err: BusinessError) => { 2717 console.info("openStream failed with error message: " + err.message + ", error code: " + err.code); 2718 }).finally(() => { 2719 fs.closeSync(file); 2720 }); 2721 ``` 2722 2723## fs.fdopenStream 2724 2725fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void 2726 2727Opens a stream based on the file descriptor. This API uses an asynchronous callback to return the result. 2728 2729**System capability**: SystemCapability.FileManagement.File.FileIO 2730 2731**Parameters** 2732 2733 | Name | Type | Mandatory | Description | 2734 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 2735 | fd | number | Yes | FD of the file. | 2736 | 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).| 2737 | callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is created asynchronously. | 2738 2739**Error codes** 2740 2741For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2742 2743**Example** 2744 2745 ```ts 2746 import { BusinessError } from '@ohos.base'; 2747 let filePath = pathDir + "/test.txt"; 2748 let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); 2749 fs.fdopenStream(file.fd, "r+", (err: BusinessError, stream: fs.Stream) => { 2750 if (err) { 2751 console.info("fdopen stream failed with error message: " + err.message + ", error code: " + err.code); 2752 } else { 2753 console.info("fdopen stream success"); 2754 stream.closeSync(); 2755 } 2756 fs.closeSync(file); 2757 }); 2758 ``` 2759 2760## fs.fdopenStreamSync 2761 2762fdopenStreamSync(fd: number, mode: string): Stream 2763 2764Opens a stream based on the file descriptor. This API returns the result synchronously. 2765 2766**System capability**: SystemCapability.FileManagement.File.FileIO 2767 2768**Parameters** 2769 2770 | Name | Type | Mandatory | Description | 2771 | ---- | ------ | ---- | ---------------------------------------- | 2772 | fd | number | Yes | FD of the file. | 2773 | 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).| 2774 2775**Return value** 2776 2777 | Type | Description | 2778 | ------------------ | --------- | 2779 | [Stream](#stream) | Stream opened.| 2780 2781**Error codes** 2782 2783For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2784 2785**Example** 2786 2787 ```ts 2788 let filePath = pathDir + "/test.txt"; 2789 let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE); 2790 let ss = fs.fdopenStreamSync(file.fd, "r+"); 2791 ss.closeSync(); 2792 fs.closeSync(file); 2793 ``` 2794 2795## fs.createWatcher<sup>10+</sup> 2796 2797createWatcher(path: string, events: number, listener: WatchEventListener): Watcher 2798 2799Creates a **Watcher** object to observe file or directory changes. 2800 2801**System capability**: SystemCapability.FileManagement.File.FileIO 2802 2803**Parameters** 2804 2805 | Name | Type | Mandatory | Description | 2806 | ---- | ------ | ---- | ---------------------------------------- | 2807 | path | string | Yes | Application sandbox path of the file or directory to observe. | 2808 | 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**: Metadata is modified.<br>- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.<br>- **0x10: IN_CLOSE_NOWRITE**: The file or directory opened is closed without being 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.| 2809 | listener | WatchEventListener | Yes | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs. | 2810 2811**Return value** 2812 2813 | Type | Description | 2814 | ------------------ | --------- | 2815 | [Watcher](#watcher10) | **Watcher** object created.| 2816 2817**Error codes** 2818 2819For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2820 2821**Example** 2822 2823 ```ts 2824 import fs, { WatchEvent } from '@ohos.file.fs'; 2825 let filePath = pathDir + "/test.txt"; 2826 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 2827 let watcher = fs.createWatcher(filePath, 0x2 | 0x10, (watchEvent: WatchEvent) => { 2828 if (watchEvent.event == 0x2) { 2829 console.info(watchEvent.fileName + 'was modified'); 2830 } else if (watchEvent.event == 0x10) { 2831 console.info(watchEvent.fileName + 'was closed'); 2832 } 2833 }); 2834 watcher.start(); 2835 fs.writeSync(file.fd, 'test'); 2836 fs.closeSync(file); 2837 watcher.stop(); 2838 ``` 2839 2840## WatchEventListener<sup>10+</sup> 2841 2842(event: WatchEvent): void 2843 2844Called when an observed event occurs. 2845 2846**System capability**: SystemCapability.FileManagement.File.FileIO 2847 2848**Parameters** 2849 2850 | Name | Type | Mandatory | Description | 2851 | ---- | ------ | ---- | ---------------------------------------- | 2852 | event | WatchEvent | Yes | Event for the callback to invoke. | 2853 2854## WatchEvent<sup>10+</sup> 2855 2856Defines the event to observe. 2857 2858**System capability**: SystemCapability.FileManagement.File.FileIO 2859 2860| Name | Type | Readable | Writable | Description | 2861| ---- | ------ | ---- | ---- | ------- | 2862| fileName | string | Yes | No | Name of the file for which the event occurs.| 2863| event | number | Yes | No | Events to observe. For details, see **events** in [createWatcher](#fscreatewatcher10).| 2864| 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.| 2865 2866## Stat 2867 2868Represents detailed file information. Before calling any API of the **Stat()** class, use [stat()](#fsstat) to create a **Stat** instance synchronously or asynchronously. 2869 2870**System capability**: SystemCapability.FileManagement.File.FileIO 2871 2872### Attributes 2873 2874| Name | Type | Readable | Writable | Description | 2875| ------ | ------ | ---- | ---- | ---------------------------------------- | 2876| ino | number | Yes | No | File ID. Different files on the same device have different **ino**s.| | 2877| 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 returned 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 or a directory entry.<br>- **0o002**: Other users have the permission to write a regular file or create and delete a directory entry.<br>- **0o001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| 2878| uid | number | Yes | No | ID of the file owner.| 2879| gid | number | Yes | No | ID of the user group of the file.| 2880| size | number | Yes | No | File size, in bytes. This parameter is valid only for regular files. | 2881| atime | number | Yes | No | Time of the last access to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | 2882| mtime | number | Yes | No | Time of the last modification to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | 2883| ctime | number | Yes | No | Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | 2884 2885### isBlockDevice 2886 2887isBlockDevice(): boolean 2888 2889Checks whether this file is a block special file. A block special file supports access by block only, and it is cached when accessed. 2890 2891**System capability**: SystemCapability.FileManagement.File.FileIO 2892 2893**Return value** 2894 2895 | Type | Description | 2896 | ------- | ---------------- | 2897 | boolean | Whether the file is a block special file.| 2898 2899**Error codes** 2900 2901For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2902 2903**Example** 2904 2905 ```ts 2906 let filePath = pathDir + "/test.txt"; 2907 let isBLockDevice = fs.statSync(filePath).isBlockDevice(); 2908 ``` 2909 2910### isCharacterDevice 2911 2912isCharacterDevice(): boolean 2913 2914Checks whether this file is a character special file. A character special file supports random access, and it is not cached when accessed. 2915 2916**System capability**: SystemCapability.FileManagement.File.FileIO 2917 2918**Return value** 2919 2920 | Type | Description | 2921 | ------- | ----------------- | 2922 | boolean | Whether the file is a character special file.| 2923 2924**Error codes** 2925 2926For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2927 2928**Example** 2929 2930 ```ts 2931 let filePath = pathDir + "/test.txt"; 2932 let isCharacterDevice = fs.statSync(filePath).isCharacterDevice(); 2933 ``` 2934 2935### isDirectory 2936 2937isDirectory(): boolean 2938 2939Checks whether this file is a directory. 2940 2941**System capability**: SystemCapability.FileManagement.File.FileIO 2942 2943**Return value** 2944 2945 | Type | Description | 2946 | ------- | ------------- | 2947 | boolean | Whether the file is a directory.| 2948 2949**Error codes** 2950 2951For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2952 2953**Example** 2954 2955 ```ts 2956 let dirPath = pathDir + "/test"; 2957 let isDirectory = fs.statSync(dirPath).isDirectory(); 2958 ``` 2959 2960### isFIFO 2961 2962isFIFO(): boolean 2963 2964Checks whether this file is a named pipe (or FIFO). Named pipes are used for inter-process communication. 2965 2966**System capability**: SystemCapability.FileManagement.File.FileIO 2967 2968**Return value** 2969 2970 | Type | Description | 2971 | ------- | --------------------- | 2972 | boolean | Whether the file is an FIFO.| 2973 2974**Error codes** 2975 2976For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 2977 2978**Example** 2979 2980 ```ts 2981 let filePath = pathDir + "/test.txt"; 2982 let isFIFO = fs.statSync(filePath).isFIFO(); 2983 ``` 2984 2985### isFile 2986 2987isFile(): boolean 2988 2989Checks whether this file is a regular file. 2990 2991**System capability**: SystemCapability.FileManagement.File.FileIO 2992 2993**Return value** 2994 2995 | Type | Description | 2996 | ------- | --------------- | 2997 | boolean | Whether the file is a regular file.| 2998 2999**Error codes** 3000 3001For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3002 3003**Example** 3004 3005 ```ts 3006 let filePath = pathDir + "/test.txt"; 3007 let isFile = fs.statSync(filePath).isFile(); 3008 ``` 3009 3010### isSocket 3011 3012isSocket(): boolean 3013 3014Checks whether this file is a socket. 3015 3016**System capability**: SystemCapability.FileManagement.File.FileIO 3017 3018**Return value** 3019 3020 | Type | Description | 3021 | ------- | -------------- | 3022 | boolean | Whether the file is a socket.| 3023 3024**Error codes** 3025 3026For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3027 3028**Example** 3029 3030 ```ts 3031 let filePath = pathDir + "/test.txt"; 3032 let isSocket = fs.statSync(filePath).isSocket(); 3033 ``` 3034 3035### isSymbolicLink 3036 3037isSymbolicLink(): boolean 3038 3039Checks whether this file is a symbolic link. 3040 3041**System capability**: SystemCapability.FileManagement.File.FileIO 3042 3043**Return value** 3044 3045 | Type | Description | 3046 | ------- | --------------- | 3047 | boolean | Whether the file is a symbolic link.| 3048 3049**Error codes** 3050 3051For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3052 3053**Example** 3054 3055 ```ts 3056 let filePath = pathDir + "/test"; 3057 let isSymbolicLink = fs.statSync(filePath).isSymbolicLink(); 3058 ``` 3059 3060## Stream 3061 3062Provides a stream for file operations. Before calling any API of the **Stream** class, use **createStream()** to create a **Stream** instance synchronously or asynchronously. 3063 3064### close 3065 3066close(): Promise<void> 3067 3068Closes the stream. This API uses a promise to return the result. 3069 3070**System capability**: SystemCapability.FileManagement.File.FileIO 3071 3072**Return value** 3073 3074 | Type | Description | 3075 | ------------------- | ------------- | 3076 | Promise<void> | Promise used to return the result.| 3077 3078**Error codes** 3079 3080For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3081 3082**Example** 3083 3084 ```ts 3085 import { BusinessError } from '@ohos.base'; 3086 let filePath = pathDir + "/test.txt"; 3087 let ss = fs.createStreamSync(filePath, "r+"); 3088 ss.close().then(() => { 3089 console.info("File stream closed"); 3090 }).catch((err: BusinessError) => { 3091 console.info("close fileStream failed with error message: " + err.message + ", error code: " + err.code); 3092 }); 3093 ``` 3094 3095### close 3096 3097close(callback: AsyncCallback<void>): void 3098 3099Closes the stream. This API uses an asynchronous callback to return the result. 3100 3101**System capability**: SystemCapability.FileManagement.File.FileIO 3102 3103**Parameters** 3104 3105 | Name | Type | Mandatory | Description | 3106 | -------- | ------------------------- | ---- | ------------- | 3107 | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the stream is closed.| 3108 3109**Error codes** 3110 3111For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3112 3113**Example** 3114 3115 ```ts 3116 import { BusinessError } from '@ohos.base'; 3117 let filePath = pathDir + "/test.txt"; 3118 let ss = fs.createStreamSync(filePath, "r+"); 3119 ss.close((err: BusinessError) => { 3120 if (err) { 3121 console.info("close stream failed with error message: " + err.message + ", error code: " + err.code); 3122 } else { 3123 console.info("close stream success"); 3124 } 3125 }); 3126 ``` 3127 3128### closeSync 3129 3130closeSync(): void 3131 3132Closes the stream. This API returns the result synchronously. 3133 3134**System capability**: SystemCapability.FileManagement.File.FileIO 3135 3136**Error codes** 3137 3138For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3139 3140**Example** 3141 3142 ```ts 3143 let filePath = pathDir + "/test.txt"; 3144 let ss = fs.createStreamSync(filePath, "r+"); 3145 ss.closeSync(); 3146 ``` 3147 3148### flush 3149 3150flush(): Promise<void> 3151 3152Flushes the stream. This API uses a promise to return the result. 3153 3154**System capability**: SystemCapability.FileManagement.File.FileIO 3155 3156**Return value** 3157 3158 | Type | Description | 3159 | ------------------- | ------------- | 3160 | Promise<void> | Promise used to return the result.| 3161 3162**Error codes** 3163 3164For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3165 3166**Example** 3167 3168 ```ts 3169 import { BusinessError } from '@ohos.base'; 3170 let filePath = pathDir + "/test.txt"; 3171 let ss = fs.createStreamSync(filePath, "r+"); 3172 ss.flush().then(() => { 3173 console.info("Stream flushed"); 3174 }).catch((err: BusinessError) => { 3175 console.info("flush failed with error message: " + err.message + ", error code: " + err.code); 3176 }); 3177 ``` 3178 3179### flush 3180 3181flush(callback: AsyncCallback<void>): void 3182 3183Flushes the stream. 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 | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| 3192 3193**Error codes** 3194 3195For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3196 3197**Example** 3198 3199 ```ts 3200 import { BusinessError } from '@ohos.base'; 3201 let filePath = pathDir + "/test.txt"; 3202 let ss = fs.createStreamSync(filePath, "r+"); 3203 ss.flush((err: BusinessError) => { 3204 if (err) { 3205 console.info("flush stream failed with error message: " + err.message + ", error code: " + err.code); 3206 } else { 3207 console.info("flush success"); 3208 } 3209 }); 3210 ``` 3211 3212### flushSync 3213 3214flushSync(): void 3215 3216Flushes the stream. This API returns the result synchronously. 3217 3218**System capability**: SystemCapability.FileManagement.File.FileIO 3219 3220**Error codes** 3221 3222For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3223 3224**Example** 3225 3226 ```ts 3227 let filePath = pathDir + "/test.txt"; 3228 let ss = fs.createStreamSync(filePath, "r+"); 3229 ss.flushSync(); 3230 ``` 3231 3232### write 3233 3234write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<number> 3235 3236Writes data into the stream. This API uses a promise to return the result. 3237 3238**System capability**: SystemCapability.FileManagement.File.FileIO 3239 3240**Parameters** 3241 3242 | Name | Type | Mandatory | Description | 3243 | ------- | ------------------------------- | ---- | ---------------------------------------- | 3244 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 3245 | options | Object | 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.| 3246 3247**Return value** 3248 3249 | Type | Description | 3250 | --------------------- | -------- | 3251 | Promise<number> | Promise used to return the length of the data written.| 3252 3253**Error codes** 3254 3255For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3256 3257**Example** 3258 3259 ```ts 3260 import { BusinessError } from '@ohos.base'; 3261 let filePath = pathDir + "/test.txt"; 3262 let ss = fs.createStreamSync(filePath, "r+"); 3263 class Option { 3264 offset: number = 0; 3265 length: number = 0; 3266 encoding: string = 'utf-8'; 3267 } 3268 let option = new Option(); 3269 option.offset = 5; 3270 option.length = 5; 3271 ss.write("hello, world", option).then((number: number) => { 3272 console.info("write succeed and size is:" + number); 3273 }).catch((err: BusinessError) => { 3274 console.info("write failed with error message: " + err.message + ", error code: " + err.code); 3275 }); 3276 ``` 3277 3278### write 3279 3280write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<number>): void 3281 3282Writes data into the stream. This API uses an asynchronous callback to return the result. 3283 3284**System capability**: SystemCapability.FileManagement.File.FileIO 3285 3286**Parameters** 3287 3288 | Name | Type | Mandatory| Description | 3289 | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 3290 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 3291 | options | Object | 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.| 3292 | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | 3293 3294**Error codes** 3295 3296For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3297 3298**Example** 3299 3300 ```ts 3301 import { BusinessError } from '@ohos.base'; 3302 let filePath = pathDir + "/test.txt"; 3303 let ss = fs.createStreamSync(filePath, "r+"); 3304 class Option { 3305 offset: number = 0; 3306 length: number = 0; 3307 encoding: string = 'utf-8'; 3308 } 3309 let option = new Option(); 3310 option.offset = 5; 3311 option.length = 5; 3312 ss.write("hello, world", option, (err: BusinessError, bytesWritten: number) => { 3313 if (err) { 3314 console.info("write stream failed with error message: " + err.message + ", error code: " + err.code); 3315 } else { 3316 if (bytesWritten) { 3317 console.info("write succeed and size is:" + bytesWritten); 3318 } 3319 } 3320 }); 3321 ``` 3322 3323### writeSync 3324 3325writeSync(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number 3326 3327Writes data into the stream. This API returns the result synchronously. 3328 3329**System capability**: SystemCapability.FileManagement.File.FileIO 3330 3331**Parameters** 3332 3333 | Name | Type | Mandatory | Description | 3334 | ------- | ------------------------------- | ---- | ---------------------------------------- | 3335 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 3336 | options | Object | 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.| 3337 3338**Return value** 3339 3340 | Type | Description | 3341 | ------ | -------- | 3342 | number | Length of the data written in the file.| 3343 3344**Error codes** 3345 3346For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3347 3348**Example** 3349 3350 ```ts 3351 let filePath = pathDir + "/test.txt"; 3352 let ss = fs.createStreamSync(filePath,"r+"); 3353 class Option { 3354 offset: number = 0; 3355 length: number = 0; 3356 encoding: string = 'utf-8'; 3357 } 3358 let option = new Option(); 3359 option.offset = 5; 3360 option.length = 5; 3361 let num = ss.writeSync("hello, world", option); 3362 ``` 3363 3364### read 3365 3366read(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise<number> 3367 3368Reads data from the stream. This API uses a promise to return the result. 3369 3370**System capability**: SystemCapability.FileManagement.File.FileIO 3371 3372**Parameters** 3373 3374 | Name | Type | Mandatory | Description | 3375 | ------- | ----------- | ---- | ---------------------------------------- | 3376 | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | 3377 | options | Object | 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.| 3378 3379**Return value** 3380 3381 | Type | Description | 3382 | ---------------------------------- | ------ | 3383 | Promise<number> | Promise used to return the data read.| 3384 3385**Error codes** 3386 3387For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3388 3389**Example** 3390 3391 ```ts 3392 import { BusinessError } from '@ohos.base'; 3393 import buffer from '@ohos.buffer'; 3394 let filePath = pathDir + "/test.txt"; 3395 let ss = fs.createStreamSync(filePath, "r+"); 3396 let arrayBuffer = new ArrayBuffer(4096); 3397 class Option { 3398 offset: number = 0; 3399 length: number = 0; 3400 } 3401 let option = new Option(); 3402 option.offset = 5; 3403 option.length = 5; 3404 ss.read(arrayBuffer, option).then((readLen: number) => { 3405 console.info("Read data successfully"); 3406 let buf = buffer.from(arrayBuffer, 0, readLen); 3407 console.log(`The content of file: ${buf.toString()}`); 3408 }).catch((err: BusinessError) => { 3409 console.info("read data failed with error message: " + err.message + ", error code: " + err.code); 3410 }); 3411 ``` 3412 3413### read 3414 3415read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }, callback: AsyncCallback<number>): void 3416 3417Reads data from the stream. This API uses an asynchronous callback to return the result. 3418 3419**System capability**: SystemCapability.FileManagement.File.FileIO 3420 3421**Parameters** 3422 3423 | Name | Type | Mandatory | Description | 3424 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3425 | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | 3426 | options | Object | 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.| 3427 | callback | AsyncCallback<number> | Yes | Callback invoked when data is read asynchronously from the stream. | 3428 3429**Error codes** 3430 3431For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3432 3433**Example** 3434 3435 ```ts 3436 import { BusinessError } from '@ohos.base'; 3437 import buffer from '@ohos.buffer'; 3438 let filePath = pathDir + "/test.txt"; 3439 let ss = fs.createStreamSync(filePath, "r+"); 3440 let arrayBuffer = new ArrayBuffer(4096); 3441 class Option { 3442 offset: number = 0; 3443 length: number = 0; 3444 } 3445 let option = new Option(); 3446 option.offset = 5; 3447 option.length = 5; 3448 ss.read(arrayBuffer, option, (err: BusinessError, readLen: number) => { 3449 if (err) { 3450 console.info("read stream failed with error message: " + err.message + ", error code: " + err.code); 3451 } else { 3452 console.info("Read data successfully"); 3453 let buf = buffer.from(arrayBuffer, 0, readLen); 3454 console.log(`The content of file: ${buf.toString()}`); 3455 } 3456 }); 3457 ``` 3458 3459### readSync 3460 3461readSync(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number 3462 3463Reads data from the stream. This API returns the result synchronously. 3464 3465**System capability**: SystemCapability.FileManagement.File.FileIO 3466 3467**Parameters** 3468 3469 | Name | Type | Mandatory | Description | 3470 | ------- | ----------- | ---- | ---------------------------------------- | 3471 | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | 3472 | options | Object | 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>| 3473 3474**Return value** 3475 3476 | Type | Description | 3477 | ------ | -------- | 3478 | number | Length of the data read.| 3479 3480**Error codes** 3481 3482For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3483 3484**Example** 3485 3486 ```ts 3487 let filePath = pathDir + "/test.txt"; 3488 let ss = fs.createStreamSync(filePath, "r+"); 3489 class Option { 3490 offset: number = 0; 3491 length: number = 0; 3492 } 3493 let option = new Option(); 3494 option.offset = 5; 3495 option.length = 5; 3496 let buf = new ArrayBuffer(4096); 3497 let num = ss.readSync(buf, option); 3498 ``` 3499 3500## File 3501 3502Represents a **File** object opened by **open()**. 3503 3504**System capability**: SystemCapability.FileManagement.File.FileIO 3505 3506### Attributes 3507 3508| Name | Type | Readable | Writable | Description | 3509| ---- | ------ | ---- | ---- | ------- | 3510| fd | number | Yes | No | FD of the file.| 3511| path<sup>10+</sup> | string | Yes | No | Path of the file.| 3512| name<sup>10+</sup> | string | Yes | No | Name of the file.| 3513 3514### lock 3515 3516lock(exclusive?: boolean): Promise\<void> 3517 3518Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result. 3519 3520**System capability**: SystemCapability.FileManagement.File.FileIO 3521 3522**Parameters** 3523 3524 | Name | Type | Mandatory | Description | 3525 | ------- | ----------- | ---- | ---------------------------------------- | 3526 | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | 3527 3528**Return value** 3529 3530 | Type | Description | 3531 | ---------------------------------- | ------ | 3532 | Promise<void> | Promise that returns no value.| 3533 3534**Error codes** 3535 3536For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3537 3538**Example** 3539 3540 ```ts 3541 import { BusinessError } from '@ohos.base'; 3542 let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 3543 file.lock(true).then(() => { 3544 console.log("lock file successful"); 3545 }).catch((err: BusinessError) => { 3546 console.info("lock file failed with error message: " + err.message + ", error code: " + err.code); 3547 }).finally(() => { 3548 fs.closeSync(file); 3549 }); 3550 ``` 3551 3552### lock 3553 3554lock(exclusive?: boolean, callback: AsyncCallback\<void>): void 3555 3556Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result. 3557 3558**System capability**: SystemCapability.FileManagement.File.FileIO 3559 3560**Parameters** 3561 3562 | Name | Type | Mandatory | Description | 3563 | ------- | ----------- | ---- | ---------------------------------------- | 3564 | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | 3565 | callback | AsyncCallback<void> | Yes | Callback invoked when the file is locked. | 3566 3567**Error codes** 3568 3569For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3570 3571**Example** 3572 3573 ```ts 3574 import { BusinessError } from '@ohos.base'; 3575 let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 3576 file.lock(true, (err: BusinessError) => { 3577 if (err) { 3578 console.info("lock file failed with error message: " + err.message + ", error code: " + err.code); 3579 } else { 3580 console.log("lock file successful"); 3581 } 3582 fs.closeSync(file); 3583 }); 3584 ``` 3585 3586### tryLock 3587 3588tryLock(exclusive?: boolean): void 3589 3590Applies an exclusive lock or a shared lock on this file in non-blocking mode. 3591 3592**System capability**: SystemCapability.FileManagement.File.FileIO 3593 3594**Parameters** 3595 3596 | Name | Type | Mandatory | Description | 3597 | ------- | ----------- | ---- | ---------------------------------------- | 3598 | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | 3599 3600**Error codes** 3601 3602For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3603 3604**Example** 3605 3606 ```ts 3607 let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 3608 file.tryLock(true); 3609 console.log("lock file successful"); 3610 fs.closeSync(file); 3611 ``` 3612 3613### unlock 3614 3615unlock(): void 3616 3617Unlocks this file synchronously. 3618 3619**System capability**: SystemCapability.FileManagement.File.FileIO 3620 3621**Error codes** 3622 3623For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3624 3625**Example** 3626 3627 ```ts 3628 let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 3629 file.tryLock(true); 3630 file.unlock(); 3631 console.log("unlock file successful"); 3632 fs.closeSync(file); 3633 ``` 3634 3635 3636## RandomAccessFile 3637 3638Randomly reads and writes a stream. Before invoking any API of **RandomAccessFile**, you need to use **createRandomAccess()** to create a **RandomAccessFile** instance synchronously or asynchronously. 3639 3640**System capability**: SystemCapability.FileManagement.File.FileIO 3641 3642### Attributes 3643 3644| Name | Type | Readable | Writable | Description | 3645| ----------- | ------ | ---- | ----- | ---------------- | 3646| fd | number | Yes | No | FD of the file.| 3647| filePointer | number | Yes | Yes | Offset pointer to the **RandomAccessFile** instance.| 3648 3649### setFilePointer<sup>10+</sup> 3650 3651setFilePointer(): void 3652 3653Sets the file offset pointer. 3654 3655**System capability**: SystemCapability.FileManagement.File.FileIO 3656 3657**Error codes** 3658 3659For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3660 3661**Example** 3662 3663 ```ts 3664 let filePath = pathDir + "/test.txt"; 3665 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 3666 randomAccessFile.setFilePointer(1); 3667 randomAccessFile.close(); 3668 ``` 3669 3670 3671### close<sup>10+</sup> 3672 3673close(): void 3674 3675Closes this **RandomAccessFile** instance synchronously. 3676 3677**System capability**: SystemCapability.FileManagement.File.FileIO 3678 3679**Error codes** 3680 3681For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3682 3683**Example** 3684 3685 ```ts 3686 let filePath = pathDir + "/test.txt"; 3687 let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 3688 randomAccessFile.close(); 3689 ``` 3690 3691### write<sup>10+</sup> 3692 3693write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): Promise<number> 3694 3695Writes data into a file. This API uses a promise to return the result. 3696 3697**System capability**: SystemCapability.FileManagement.File.FileIO 3698 3699**Parameters** 3700 3701 | Name | Type | Mandatory | Description | 3702 | ------- | ------------------------------- | ---- | ---------------------------------------- | 3703 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 3704 | options | Object | 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.| 3705 3706**Return value** 3707 3708 | Type | Description | 3709 | --------------------- | -------- | 3710 | Promise<number> | Promise used to return the length of the data written.| 3711 3712**Error codes** 3713 3714For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3715 3716**Example** 3717 3718 ```ts 3719 import { BusinessError } from '@ohos.base'; 3720 let filePath = pathDir + "/test.txt"; 3721 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3722 let randomaccessfile = fs.createRandomAccessFileSync(file); 3723 let bufferLength: number = 4096; 3724 class Option { 3725 offset: number = 0; 3726 length: number = 0; 3727 encoding: string = 'utf-8'; 3728 } 3729 let option = new Option(); 3730 option.offset = 1; 3731 option.length = 5; 3732 let arrayBuffer = new ArrayBuffer(bufferLength); 3733 randomaccessfile.write(arrayBuffer, option).then((bytesWritten: number) => { 3734 console.info("randomAccessFile bytesWritten: " + bytesWritten); 3735 }).catch((err: BusinessError) => { 3736 console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3737 }).finally(() => { 3738 randomaccessfile.close(); 3739 fs.closeSync(file); 3740 }); 3741 3742 ``` 3743 3744### write<sup>10+</sup> 3745 3746write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }, callback: AsyncCallback<number>): void 3747 3748Writes data into a file. This API uses an asynchronous callback to return the result. 3749 3750**System capability**: SystemCapability.FileManagement.File.FileIO 3751 3752**Parameters** 3753 3754 | Name | Type | Mandatory| Description | 3755 | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | 3756 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 3757 | options | Object | 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.| 3758 | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | 3759 3760**Error codes** 3761 3762For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3763 3764**Example** 3765 3766 ```ts 3767 import { BusinessError } from '@ohos.base'; 3768 let filePath = pathDir + "/test.txt"; 3769 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3770 let randomAccessFile = fs.createRandomAccessFileSync(file); 3771 let bufferLength: number = 4096; 3772 class Option { 3773 offset: number = 0; 3774 length: number = bufferLength; 3775 encoding: string = 'utf-8'; 3776 } 3777 let option = new Option(); 3778 option.offset = 1; 3779 let arrayBuffer = new ArrayBuffer(bufferLength); 3780 randomAccessFile.write(arrayBuffer, option, (err: BusinessError, bytesWritten: number) => { 3781 if (err) { 3782 console.info("write failed with error message: " + err.message + ", error code: " + err.code); 3783 } else { 3784 if (bytesWritten) { 3785 console.info("write succeed and size is:" + bytesWritten); 3786 } 3787 } 3788 randomAccessFile.close(); 3789 fs.closeSync(file); 3790 }); 3791 ``` 3792 3793### writeSync<sup>10+</sup> 3794 3795writeSync(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; encoding?: string; }): number 3796 3797Writes data into a file. This API returns the result synchronously. 3798 3799**System capability**: SystemCapability.FileManagement.File.FileIO 3800 3801**Parameters** 3802 3803 | Name | Type | Mandatory | Description | 3804 | ------- | ------------------------------- | ---- | ---------------------------------------- | 3805 | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | 3806 | options | Object | 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.| 3807 3808**Return value** 3809 3810 | Type | Description | 3811 | ------ | -------- | 3812 | number | Length of the data written in the file.| 3813 3814**Error codes** 3815 3816For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3817 3818**Example** 3819 3820 ```ts 3821 let filePath = pathDir + "/test.txt"; 3822 let randomaccessfile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3823 class Option { 3824 offset: number = 0; 3825 length: number = 0; 3826 encoding: string = 'utf-8'; 3827 } 3828 let option = new Option(); 3829 option.offset = 5; 3830 option.length = 5; 3831 let bytesWritten = randomaccessfile.writeSync("hello, world", option); 3832 randomaccessfile.close(); 3833 fs.closeSync(file); 3834 ``` 3835 3836### read<sup>10+</sup> 3837 3838read(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): Promise<number> 3839 3840Reads data from a file. This API uses a promise to return the result. 3841 3842**System capability**: SystemCapability.FileManagement.File.FileIO 3843 3844**Parameters** 3845 3846 | Name | Type | Mandatory | Description | 3847 | ------- | ----------- | ---- | ---------------------------------------- | 3848 | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | 3849 | options | Object | 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**.| 3850 3851**Return value** 3852 3853 | Type | Description | 3854 | ---------------------------------- | ------ | 3855 | Promise<number> | Promise used to return the data read.| 3856 3857**Error codes** 3858 3859For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3860 3861**Example** 3862 3863 ```ts 3864 import { BusinessError } from '@ohos.base'; 3865 let filePath = pathDir + "/test.txt"; 3866 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3867 let randomaccessfile = fs.createRandomAccessFileSync(file); 3868 let bufferLength: number = 4096; 3869 class Option { 3870 offset: number = 0; 3871 length: number = bufferLength; 3872 } 3873 let option = new Option(); 3874 option.offset = 1; 3875 option.length = 5; 3876 let arrayBuffer = new ArrayBuffer(bufferLength); 3877 randomaccessfile.read(arrayBuffer, option).then((readLength: number) => { 3878 console.info("randomAccessFile readLength: " + readLength); 3879 randomaccessfile.close(); 3880 fs.closeSync(file); 3881 }).catch((err: BusinessError) => { 3882 console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); 3883 }).finally(() => { 3884 randomaccessfile.close(); 3885 fs.closeSync(file); 3886 }); 3887 ``` 3888 3889### read<sup>10+</sup> 3890 3891read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }, callback: AsyncCallback<number>): void 3892 3893Reads data from a file. This API uses an asynchronous callback to return the result. 3894 3895**System capability**: SystemCapability.FileManagement.File.FileIO 3896 3897**Parameters** 3898 3899 | Name | Type | Mandatory | Description | 3900 | -------- | ---------------------------------------- | ---- | ---------------------------------------- | 3901 | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | 3902 | options | Object | 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**.| 3903 | callback | AsyncCallback<number> | Yes | Callback invoked when data is read asynchronously from the stream. | 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 file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3915 let randomaccessfile = fs.createRandomAccessFileSync(file); 3916 let length: number = 20; 3917 class Option { 3918 offset: number = 0; 3919 length: number = length; 3920 } 3921 let option = new Option(); 3922 option.offset = 1; 3923 option.length = 5; 3924 let arrayBuffer = new ArrayBuffer(length); 3925 randomaccessfile.read(arrayBuffer, option, (err: BusinessError, readLength: number) => { 3926 if (err) { 3927 console.info("read failed with error message: " + err.message + ", error code: " + err.code); 3928 } else { 3929 if (readLength) { 3930 console.info("read succeed and size is:" + readLength); 3931 } 3932 } 3933 randomAccessFile.close(); 3934 fs.closeSync(file); 3935 }); 3936 ``` 3937 3938### readSync<sup>10+</sup> 3939 3940readSync(buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number 3941 3942Reads data from a file. This API returns the result synchronously. 3943 3944**System capability**: SystemCapability.FileManagement.File.FileIO 3945 3946**Parameters** 3947 3948 | Name | Type | Mandatory | Description | 3949 | ------- | ----------- | ---- | ---------------------------------------- | 3950 | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | 3951 | options | Object | 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>| 3952 3953**Return value** 3954 3955 | Type | Description | 3956 | ------ | -------- | 3957 | number | Length of the data read.| 3958 3959**Error codes** 3960 3961For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3962 3963**Example** 3964 3965 ```ts 3966 let filePath = pathDir + "/test.txt"; 3967 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 3968 let randomaccessfile = fs.createRandomAccessFileSync(file); 3969 let length: number = 4096; 3970 let arrayBuffer = new ArrayBuffer(length); 3971 let readLength = randomaccessfile.readSync(arrayBuffer); 3972 randomaccessfile.close(); 3973 fs.closeSync(file); 3974 ``` 3975 3976 3977## Watcher<sup>10+</sup> 3978 3979Provides APIs for observing the changes of files or folders. Before using the APIs of **Watcher** , call **createWatcher()** to create a **Watcher** object. 3980 3981### start<sup>10+</sup> 3982 3983start(): void 3984 3985Starts listening. 3986 3987**System capability**: SystemCapability.FileManagement.File.FileIO 3988 3989**Error codes** 3990 3991For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 3992 3993**Example** 3994 3995 ```ts 3996 let filePath = pathDir + "/test.txt"; 3997 let watcher = fs.createWatcher(filePath, 0xfff, () => {}); 3998 watcher.start(); 3999 watcher.stop(); 4000 ``` 4001 4002### stop<sup>10+</sup> 4003 4004stop(): void 4005 4006Stops listening. 4007 4008**System capability**: SystemCapability.FileManagement.File.FileIO 4009 4010**Error codes** 4011 4012For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). 4013 4014**Example** 4015 4016 ```ts 4017 let filePath = pathDir + "/test.txt"; 4018 let watcher = fs.createWatcher(filePath, 0xfff, () => {}); 4019 watcher.start(); 4020 watcher.stop(); 4021 ``` 4022 4023## OpenMode 4024 4025Defines the constants of the **mode** parameter used in **open()**. It specifies the mode for opening a file. 4026 4027**System capability**: SystemCapability.FileManagement.File.FileIO 4028 4029| Name | Type | Value | Description | 4030| ---- | ------ |---- | ------- | 4031| READ_ONLY | number | 0o0 | Open the file in read-only mode.| 4032| WRITE_ONLY | number | 0o1 | Open the file in write-only mode.| 4033| READ_WRITE | number | 0o2 | Open the file in read/write mode.| 4034| CREATE | number | 0o100 | Create a file if the specified file does not exist.| 4035| TRUNC | number | 0o1000 | If the file exists and is open in write-only or read/write mode, truncate the file length to 0.| 4036| APPEND | number | 0o2000 | Open the file in append mode. New data will be written to the end of the file.| 4037| 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.| 4038| DIR | number | 0o200000 | If **path** does not point to a directory, throw an exception.| 4039| NOFOLLOW | number | 0o400000 | If **path** points to a symbolic link, throw an exception.| 4040| SYNC | number | 0o4010000 | Open the file in synchronous I/O mode.| 4041 4042## Filter<sup>10+</sup> 4043 4044**System capability**: SystemCapability.FileManagement.File.FileIO 4045 4046Defines the file filtering configuration, which can be used by **listFile()**. 4047 4048| Name | Type | Description | 4049| ----------- | --------------- | ------------------ | 4050| suffix | Array<string> | Locate files that fully match the specified file name extensions, which are of the OR relationship. | 4051| displayName | Array<string> | Locate files that fuzzy match the specified file names, which are of the OR relationship. Currently, only the wildcard * is supported.| 4052| mimeType | Array<string> | Locate files that fully match the specified MIME types, which are of the OR relationship. | 4053| fileSizeOver | number | Locate files that are greater than or equal to the specified size. | 4054| lastModifiedAfter | number | Locate files whose last modification time is the same or later than the specified time. | 4055| excludeMedia | boolean | Whether to exclude the files already in **Media**. | 4056 4057## ConflictFiles<sup>10+</sup> 4058 4059**System capability**: SystemCapability.FileManagement.File.FileIO 4060 4061Defines information about the conflicting files. It is used the **copyDir()** and **moveDir()**. 4062 4063| Name | Type | Description | 4064| ----------- | --------------- | ------------------ | 4065| srcFile | string | Path of the source file. | 4066| destFile | string | Path of the destination file.| 4067