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