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