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使用该功能模块对文件/目录进行操作前,需要先获取其应用沙箱路径。表示沙箱路径的字符串称为path,获取方式及其接口用法请参考:[应用上下文Context-获取应用文件路径](../../application-models/application-context-stage.md#获取应用文件路径)。将指向资源的字符串称为URI。对于只支持path作为入参的接口可使用构造fileUri对象并获取其path属性的方式将URI转换为path,然后使用文件接口。URI定义解及其转换方式请参考:[文件URI](../../../application-dev/reference/apis-core-file-kit/js-apis-file-fileuri.md)
32
33## fs.stat
34
35stat(file: string | number): Promise<Stat>
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<[Stat](#stat)> | 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<Stat>): 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<[Stat](#stat)> | 是   | 异步获取文件的信息之后的回调。 |
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<boolean>
141
142检查文件是否存在,使用Promise异步返回。
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对象。返回布尔值,表示文件是否存在。 |
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异步返回。如果文件在云端,或者其它分布式设备上,返回false。
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.AccessModeFlag.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以同步方法检查文件是否存在。
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以同步方法检查文件是否在本地,或校验相关权限。如果文件在云端,或者其它分布式设备上,返回false。
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.AccessModeFlag.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对象或文件描述符不再具备实际意义,不可再用于进行读写等操作。 |
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对象或文件描述符不再具备实际意义,不可再用于进行读写等操作。 |
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对象或文件描述符不再具备实际意义,不可再用于进行读写等操作。 |
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。
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。
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。
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 | 否    | 复制模式。默认mode为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 | 是    | 复制模式。默认mode为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 | 否    | 复制模式。默认mode为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。                                   |
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。                                   |
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    }
1518    fs.closeSync(file);
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    }
1554    fs.closeSync(file);
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     |  迭代器是否已完成迭代。          |
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。 |
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**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
2566
2567**系统能力**:SystemCapability.FileManagement.File.FileIO
2568
2569**参数:**
2570
2571| 参数名  | 类型   | 必填 | 说明                         |
2572| ------- | ------ | ---- | ---------------------------- |
2573| oldPath | string | 是   | 文件的应用沙箱原路径。 |
2574| newPath | string | 是   | 文件的应用沙箱新路径。   |
2575
2576**返回值:**
2577
2578  | 类型                  | 说明                           |
2579  | ------------------- | ---------------------------- |
2580  | Promise&lt;void&gt; | Promise对象。无返回值。 |
2581
2582**错误码:**
2583
2584接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2585
2586**示例:**
2587
2588  ```ts
2589  import { BusinessError } from '@kit.BasicServicesKit';
2590  let srcFile = pathDir + "/test.txt";
2591  let dstFile = pathDir + "/new.txt";
2592  fs.rename(srcFile, dstFile).then(() => {
2593    console.info("rename succeed");
2594  }).catch((err: BusinessError) => {
2595    console.error("rename failed with error message: " + err.message + ", error code: " + err.code);
2596  });
2597  ```
2598
2599## fs.rename
2600
2601rename(oldPath: string, newPath: string, callback: AsyncCallback&lt;void&gt;): void
2602
2603重命名文件或文件夹,使用callback异步回调。
2604
2605> **说明:**
2606> 该接口不支持在分布式文件路径下操作。
2607
2608**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
2609
2610**系统能力**:SystemCapability.FileManagement.File.FileIO
2611
2612**参数:**
2613
2614| 参数名   | 类型                      | 必填 | 说明                         |
2615| -------- | ------------------------- | ---- | ---------------------------- |
2616| oldPath | string | 是   | 文件的应用沙箱原路径。 |
2617| newPath | string | 是   | 文件的应用沙箱新路径。   |
2618| callback | AsyncCallback&lt;void&gt; | 是   | 异步重命名文件之后的回调。   |
2619
2620**错误码:**
2621
2622接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2623
2624**示例:**
2625
2626  ```ts
2627  import { BusinessError } from '@kit.BasicServicesKit';
2628  let srcFile = pathDir + "/test.txt";
2629  let dstFile = pathDir + "/new.txt";
2630  fs.rename(srcFile, dstFile, (err: BusinessError) => {
2631    if (err) {
2632      console.error("rename failed with error message: " + err.message + ", error code: " + err.code);
2633    } else {
2634      console.info("rename succeed");
2635    }
2636  });
2637  ```
2638
2639## fs.renameSync
2640
2641renameSync(oldPath: string, newPath: string): void
2642
2643以同步方法重命名文件或文件夹。
2644
2645> **说明:**
2646> 该接口不支持在分布式文件路径下操作。
2647
2648**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
2649
2650**系统能力**:SystemCapability.FileManagement.File.FileIO
2651
2652**参数:**
2653
2654| 参数名  | 类型   | 必填 | 说明                         |
2655| ------- | ------ | ---- | ---------------------------- |
2656| oldPath | string | 是   | 文件的应用沙箱原路径。 |
2657| newPath | string | 是   | 文件的应用沙箱新路径。   |
2658
2659**错误码:**
2660
2661接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2662
2663**示例:**
2664
2665  ```ts
2666  let srcFile = pathDir + "/test.txt";
2667  let dstFile = pathDir + "/new.txt";
2668  fs.renameSync(srcFile, dstFile);
2669  ```
2670
2671## fs.fsync
2672
2673fsync(fd: number): Promise&lt;void&gt;
2674
2675将文件系统缓存数据写入磁盘,使用Promise异步返回。
2676
2677**系统能力**:SystemCapability.FileManagement.File.FileIO
2678
2679**参数:**
2680
2681  | 参数名  | 类型     | 必填   | 说明           |
2682  | ---- | ------ | ---- | ------------ |
2683  | fd   | number | 是    | 已打开的文件描述符。 |
2684
2685**返回值:**
2686
2687  | 类型                  | 说明                           |
2688  | ------------------- | ---------------------------- |
2689  | Promise&lt;void&gt; | Promise对象。无返回值。 |
2690
2691**错误码:**
2692
2693接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2694
2695**示例:**
2696
2697  ```ts
2698  import { BusinessError } from '@kit.BasicServicesKit';
2699  let filePath = pathDir + "/test.txt";
2700  let file = fs.openSync(filePath);
2701  fs.fsync(file.fd).then(() => {
2702    console.info("sync data succeed");
2703  }).catch((err: BusinessError) => {
2704    console.error("sync data failed with error message: " + err.message + ", error code: " + err.code);
2705  }).finally(() => {
2706    fs.closeSync(file);
2707  });
2708  ```
2709
2710## fs.fsync
2711
2712fsync(fd: number, callback: AsyncCallback&lt;void&gt;): void
2713
2714将文件系统缓存数据写入磁盘,使用callback异步回调。
2715
2716**系统能力**:SystemCapability.FileManagement.File.FileIO
2717
2718**参数:**
2719
2720  | 参数名      | 类型                        | 必填   | 说明              |
2721  | -------- | ------------------------- | ---- | --------------- |
2722  | fd       | number                    | 是    | 已打开的文件描述符。    |
2723  | Callback | AsyncCallback&lt;void&gt; | 是    | 异步将文件数据同步之后的回调。 |
2724
2725**错误码:**
2726
2727接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2728
2729**示例:**
2730
2731  ```ts
2732  import { BusinessError } from '@kit.BasicServicesKit';
2733  let filePath = pathDir + "/test.txt";
2734  let file = fs.openSync(filePath);
2735  fs.fsync(file.fd, (err: BusinessError) => {
2736    if (err) {
2737      console.error("fsync failed with error message: " + err.message + ", error code: " + err.code);
2738    } else {
2739      console.info("fsync succeed");
2740    }
2741    fs.closeSync(file);
2742  });
2743  ```
2744
2745
2746## fs.fsyncSync
2747
2748fsyncSync(fd: number): void
2749
2750以同步方法将文件系统缓存数据写入磁盘。
2751
2752**系统能力**:SystemCapability.FileManagement.File.FileIO
2753
2754**参数:**
2755
2756  | 参数名  | 类型     | 必填   | 说明           |
2757  | ---- | ------ | ---- | ------------ |
2758  | fd   | number | 是    | 已打开的文件描述符。 |
2759
2760**错误码:**
2761
2762接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2763
2764**示例:**
2765
2766  ```ts
2767  let filePath = pathDir + "/test.txt";
2768  let file = fs.openSync(filePath);
2769  fs.fsyncSync(file.fd);
2770  fs.closeSync(file);
2771  ```
2772
2773## fs.fdatasync
2774
2775fdatasync(fd: number): Promise&lt;void&gt;
2776
2777实现文件内容数据同步,使用Promise异步返回。
2778
2779**系统能力**:SystemCapability.FileManagement.File.FileIO
2780
2781**参数:**
2782
2783  | 参数名  | 类型     | 必填   | 说明           |
2784  | ---- | ------ | ---- | ------------ |
2785  | fd   | number | 是    | 已打开的文件描述符。 |
2786
2787**返回值:**
2788
2789  | 类型                  | 说明                           |
2790  | ------------------- | ---------------------------- |
2791  | Promise&lt;void&gt; | Promise对象。无返回值。 |
2792
2793**错误码:**
2794
2795接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2796
2797**示例:**
2798
2799  ```ts
2800  import { BusinessError } from '@kit.BasicServicesKit';
2801  let filePath = pathDir + "/test.txt";
2802  let file = fs.openSync(filePath);
2803  fs.fdatasync(file.fd).then(() => {
2804    console.info("sync data succeed");
2805  }).catch((err: BusinessError) => {
2806    console.error("sync data failed with error message: " + err.message + ", error code: " + err.code);
2807  }).finally(() => {
2808    fs.closeSync(file);
2809  });
2810  ```
2811
2812## fs.fdatasync
2813
2814fdatasync(fd: number, callback: AsyncCallback&lt;void&gt;): void
2815
2816实现文件内容数据同步,使用callback异步回调。
2817
2818**系统能力**:SystemCapability.FileManagement.File.FileIO
2819
2820**参数:**
2821
2822  | 参数名      | 类型                              | 必填   | 说明                |
2823  | -------- | ------------------------------- | ---- | ----------------- |
2824  | fd       | number                          | 是    | 已打开的文件描述符。      |
2825  | callback | AsyncCallback&lt;void&gt; | 是    | 异步将文件内容数据同步之后的回调。 |
2826
2827**错误码:**
2828
2829接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2830
2831**示例:**
2832
2833  ```ts
2834  import { BusinessError } from '@kit.BasicServicesKit';
2835  let filePath = pathDir + "/test.txt";
2836  let file = fs.openSync(filePath);
2837  fs.fdatasync (file.fd, (err: BusinessError) => {
2838    if (err) {
2839      console.error("fdatasync failed with error message: " + err.message + ", error code: " + err.code);
2840    } else {
2841      console.info("fdatasync succeed");
2842    }
2843    fs.closeSync(file);
2844  });
2845  ```
2846
2847## fs.fdatasyncSync
2848
2849fdatasyncSync(fd: number): void
2850
2851以同步方法实现文件内容数据同步。
2852
2853**系统能力**:SystemCapability.FileManagement.File.FileIO
2854
2855**参数:**
2856
2857  | 参数名  | 类型     | 必填   | 说明           |
2858  | ---- | ------ | ---- | ------------ |
2859  | fd   | number | 是    | 已打开的文件描述符。 |
2860
2861**错误码:**
2862
2863接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2864
2865**示例:**
2866
2867  ```ts
2868  let filePath = pathDir + "/test.txt";
2869  let file = fs.openSync(filePath);
2870  fs.fdatasyncSync(file.fd);
2871  fs.closeSync(file);
2872  ```
2873
2874## fs.symlink
2875
2876symlink(target: string, srcPath: string): Promise&lt;void&gt;
2877
2878基于文件路径创建符号链接,使用Promise异步返回。
2879
2880**系统能力**:SystemCapability.FileManagement.File.FileIO
2881
2882**参数:**
2883
2884| 参数名  | 类型   | 必填 | 说明                         |
2885| ------- | ------ | ---- | ---------------------------- |
2886| target  | string | 是   | 源文件的应用沙箱路径。     |
2887| srcPath | string | 是   | 符号链接文件的应用沙箱路径。 |
2888
2889**返回值:**
2890
2891  | 类型                  | 说明                           |
2892  | ------------------- | ---------------------------- |
2893  | Promise&lt;void&gt; | Promise对象。无返回值。 |
2894
2895**错误码:**
2896
2897接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2898
2899**示例:**
2900
2901  ```ts
2902  import { BusinessError } from '@kit.BasicServicesKit';
2903  let srcFile = pathDir + "/test.txt";
2904  let dstFile = pathDir + "/test";
2905  fs.symlink(srcFile, dstFile).then(() => {
2906    console.info("symlink succeed");
2907  }).catch((err: BusinessError) => {
2908    console.error("symlink failed with error message: " + err.message + ", error code: " + err.code);
2909  });
2910  ```
2911
2912
2913## fs.symlink
2914symlink(target: string, srcPath: string, callback: AsyncCallback&lt;void&gt;): void
2915
2916基于文件路径创建符号链接,使用callback异步回调。
2917
2918**系统能力**:SystemCapability.FileManagement.File.FileIO
2919
2920**参数:**
2921
2922| 参数名   | 类型                      | 必填 | 说明                             |
2923| -------- | ------------------------- | ---- | -------------------------------- |
2924| target   | string                    | 是   | 源文件的应用沙箱路径。         |
2925| srcPath  | string                    | 是   | 符号链接文件的应用沙箱路径。     |
2926| callback | AsyncCallback&lt;void&gt; | 是   | 异步创建符号链接信息之后的回调。 |
2927
2928**错误码:**
2929
2930接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2931
2932**示例:**
2933
2934  ```ts
2935  import { BusinessError } from '@kit.BasicServicesKit';
2936  let srcFile = pathDir + "/test.txt";
2937  let dstFile = pathDir + "/test";
2938  fs.symlink(srcFile, dstFile, (err: BusinessError) => {
2939    if (err) {
2940      console.error("symlink failed with error message: " + err.message + ", error code: " + err.code);
2941    } else {
2942      console.info("symlink succeed");
2943    }
2944  });
2945  ```
2946
2947## fs.symlinkSync
2948
2949symlinkSync(target: string, srcPath: string): void
2950
2951以同步的方法基于文件路径创建符号链接。
2952
2953**系统能力**:SystemCapability.FileManagement.File.FileIO
2954
2955**参数:**
2956
2957| 参数名  | 类型   | 必填 | 说明                         |
2958| ------- | ------ | ---- | ---------------------------- |
2959| target  | string | 是   | 源文件的应用沙箱路径。     |
2960| srcPath | string | 是   | 符号链接文件的应用沙箱路径。 |
2961
2962**错误码:**
2963
2964接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
2965
2966**示例:**
2967
2968  ```ts
2969  let srcFile = pathDir + "/test.txt";
2970  let dstFile = pathDir + "/test";
2971  fs.symlinkSync(srcFile, dstFile);
2972  ```
2973
2974## fs.listFile
2975listFile(path: string, options?: ListFileOptions): Promise<string[]>
2976
2977列出文件夹下所有文件名,支持递归列出所有文件名(包含子目录下),支持文件过滤,使用Promise异步返回。
2978
2979**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
2980
2981**系统能力**:SystemCapability.FileManagement.File.FileIO
2982
2983**参数:**
2984
2985  | 参数名    | 类型     | 必填   | 说明                          |
2986  | ------ | ------ | ---- | --------------------------- |
2987  | path | string | 是    | 文件夹的应用沙箱路径。 |
2988  | options | [ListFileOptions](#listfileoptions11) | 否    | 文件过滤选项。默认不进行过滤。 |
2989
2990
2991**返回值:**
2992
2993  | 类型                   | 说明         |
2994  | --------------------- | ---------- |
2995  | Promise&lt;string[]&gt; | Promise对象。返回文件名数组。 |
2996
2997**错误码:**
2998
2999接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3000
3001**示例:**
3002
3003  ```ts
3004  import { BusinessError } from '@kit.BasicServicesKit';
3005  import { fileIo as fs, Filter, ListFileOptions } from '@kit.CoreFileKit';
3006  let listFileOption: ListFileOptions = {
3007    recursion: false,
3008    listNum: 0,
3009    filter: {
3010      suffix: [".png", ".jpg", ".jpeg"],
3011      displayName: ["*abc", "efg*"],
3012      fileSizeOver: 1024
3013    }
3014  }
3015  fs.listFile(pathDir, listFileOption).then((filenames: Array<string>) => {
3016    console.info("listFile succeed");
3017    for (let i = 0; i < filenames.length; i++) {
3018      console.info("fileName: %s", filenames[i]);
3019    }
3020  }).catch((err: BusinessError) => {
3021    console.error("list file failed with error message: " + err.message + ", error code: " + err.code);
3022  });
3023  ```
3024
3025## fs.listFile
3026listFile(path: string, options?: ListFileOptions, callback: AsyncCallback<string[]>): void
3027
3028列出文件夹下所有文件名,支持递归列出所有文件名(包含子目录下),支持文件过滤,使用Callback异步回调。
3029
3030**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
3031
3032**系统能力**:SystemCapability.FileManagement.File.FileIO
3033
3034**参数:**
3035
3036  | 参数名    | 类型     | 必填   | 说明                          |
3037  | ------ | ------ | ---- | --------------------------- |
3038  | path | string | 是    | 文件夹的应用沙箱路径。 |
3039  | options | [ListFileOptions](#listfileoptions11) | 否    | 文件过滤选项。默认不进行过滤。 |
3040  | callback | AsyncCallback&lt;string[]&gt; | 是    | 异步列出文件名数组之后的回调。              |
3041
3042
3043**错误码:**
3044
3045接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3046
3047**示例:**
3048
3049  ```ts
3050  import { BusinessError } from '@kit.BasicServicesKit';
3051  import { fileIo as fs, Filter, ListFileOptions } from '@kit.CoreFileKit';
3052  let listFileOption: ListFileOptions = {
3053    recursion: false,
3054    listNum: 0,
3055    filter: {
3056      suffix: [".png", ".jpg", ".jpeg"],
3057      displayName: ["*abc", "efg*"],
3058      fileSizeOver: 1024
3059    }
3060  };
3061  fs.listFile(pathDir, listFileOption, (err: BusinessError, filenames: Array<string>) => {
3062    if (err) {
3063      console.error("list file failed with error message: " + err.message + ", error code: " + err.code);
3064    } else {
3065      console.info("listFile succeed");
3066      for (let i = 0; i < filenames.length; i++) {
3067        console.info("filename: %s", filenames[i]);
3068      }
3069    }
3070  });
3071  ```
3072
3073## fs.listFileSync
3074
3075listFileSync(path: string, options?: ListFileOptions): string[]
3076
3077以同步方式列出文件夹下所有文件名,支持递归列出所有文件名(包含子目录下),支持文件过滤。
3078
3079**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
3080
3081**系统能力**:SystemCapability.FileManagement.File.FileIO
3082
3083**参数:**
3084
3085  | 参数名    | 类型     | 必填   | 说明                          |
3086  | ------ | ------ | ---- | --------------------------- |
3087  | path | string | 是    | 文件夹的应用沙箱路径。 |
3088  | options | [ListFileOptions](#listfileoptions11) | 否    | 文件过滤选项。默认不进行过滤。 |
3089
3090
3091**返回值:**
3092
3093  | 类型                   | 说明         |
3094  | --------------------- | ---------- |
3095  | string[] | 返回文件名数组。 |
3096
3097**错误码:**
3098
3099接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3100
3101**示例:**
3102
3103  ```ts
3104  import { fileIo as fs, Filter, ListFileOptions} from '@kit.CoreFileKit';
3105  let listFileOption: ListFileOptions = {
3106    recursion: false,
3107    listNum: 0,
3108    filter: {
3109      suffix: [".png", ".jpg", ".jpeg"],
3110      displayName: ["*abc", "efg*"],
3111      fileSizeOver: 1024
3112    }
3113  };
3114  let filenames = fs.listFileSync(pathDir, listFileOption);
3115  console.info("listFile succeed");
3116  for (let i = 0; i < filenames.length; i++) {
3117    console.info("filename: %s", filenames[i]);
3118  }
3119  ```
3120
3121## fs.lseek<sup>11+</sup>
3122
3123lseek(fd: number, offset: number, whence?: WhenceType): number
3124
3125调整文件偏置指针位置。
3126
3127**系统能力**:SystemCapability.FileManagement.File.FileIO
3128
3129**参数:**
3130
3131  | 参数名    | 类型     | 必填   | 说明                          |
3132  | ------ | ------ | ---- | --------------------------- |
3133  | fd | number | 是    | 文件描述符。 |
3134  | offset | number | 是    | 相对偏移位置,单位为字节。 |
3135  | whence | [WhenceType](#whencetype11) | 否    | 偏移指针相对位置类型。 |
3136
3137**返回值:**
3138
3139  | 类型                   | 说明         |
3140  | --------------------- | ---------- |
3141  | number | 当前文件偏置指针位置(相对于文件头的偏移量,单位为字节)。 |
3142
3143**错误码:**
3144
3145接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3146
3147**示例:**
3148
3149  ```ts
3150  let filePath = pathDir + "/test.txt";
3151  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
3152  console.info('The current offset is at ' + fs.lseek(file.fd, 5, fs.WhenceType.SEEK_SET));
3153  fs.closeSync(file);
3154  ```
3155
3156## fs.moveDir<sup>10+</sup>
3157
3158moveDir(src: string, dest: string, mode?: number): Promise\<void>
3159
3160移动源文件夹至目标路径下,使用Promise异步返回。
3161
3162> **说明:**
3163> 该接口不支持在分布式文件路径下操作。
3164
3165**系统能力**:SystemCapability.FileManagement.File.FileIO
3166
3167**参数:**
3168
3169  | 参数名    | 类型     | 必填   | 说明                          |
3170  | ------ | ------ | ---- | --------------------------- |
3171  | src | string | 是    | 源文件夹的应用沙箱路径。 |
3172  | dest | string | 是    | 目标文件夹的应用沙箱路径。 |
3173  | mode | number | 否    | 移动模式。默认mode为0。<br/>-&nbsp;mode为0,文件夹级别抛异常。若目标文件夹下存在与源文件夹名冲突的非空文件夹,则抛出异常。<br/>-&nbsp;mode为1,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>-&nbsp; mode为2,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。<br/>-&nbsp; mode为3,文件夹级别强制覆盖。移动源文件夹至目标文件夹下,目标文件夹下移动的文件夹内容与源文件夹完全一致。若目标文件夹下存在与源文件夹名冲突的文件夹,该文件夹下所有原始文件将不会保留。|
3174
3175**返回值:**
3176
3177  | 类型                  | 说明                           |
3178  | ------------------- | ---------------------------- |
3179  | Promise&lt;void&gt; | Promise对象。无返回值。 |
3180
3181**错误码:**
3182
3183接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3184
3185**示例:**
3186
3187  ```ts
3188  import { BusinessError } from '@kit.BasicServicesKit';
3189  // move directory from srcPath to destPath
3190  let srcPath = pathDir + "/srcDir/";
3191  let destPath = pathDir + "/destDir/";
3192  fs.moveDir(srcPath, destPath, 1).then(() => {
3193    console.info("move directory succeed");
3194  }).catch((err: BusinessError) => {
3195    console.error("move directory failed with error message: " + err.message + ", error code: " + err.code);
3196  });
3197  ```
3198
3199## fs.moveDir<sup>10+</sup>
3200
3201moveDir(src: string, dest: string, mode: number, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void
3202
3203移动源文件夹至目标路径下,支持设置移动模式。使用callback异步回调。
3204
3205> **说明:**
3206> 该接口不支持在分布式文件路径下操作。
3207
3208**系统能力**:SystemCapability.FileManagement.File.FileIO
3209
3210**参数:**
3211
3212  | 参数名    | 类型     | 必填   | 说明                          |
3213  | ------ | ------ | ---- | --------------------------- |
3214  | src | string | 是    | 源文件夹的应用沙箱路径。 |
3215  | dest | string | 是    | 目标文件夹的应用沙箱路径。 |
3216  | mode | number | 是    | 移动模式。默认mode为0。<br/>-&nbsp;mode为0,文件夹级别抛异常。若目标文件夹下存在与源文件夹名冲突的文件夹,则抛出异常。<br/>-&nbsp;mode为1,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>-&nbsp; mode为2,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。<br/>-&nbsp; mode为3,文件夹级别强制覆盖。移动源文件夹至目标文件夹下,目标文件夹下移动的文件夹内容与源文件夹完全一致。若目标文件夹下存在与源文件夹名冲突的文件夹,该文件夹下所有原始文件将不会保留。|
3217  | callback | AsyncCallback&lt;void, Array&lt;[ConflictFiles](#conflictfiles10)&gt;&gt; | 是    | 异步移动文件夹之后的回调。              |
3218
3219**错误码:**
3220
3221接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3222
3223**示例:**
3224
3225  ```ts
3226  import { BusinessError } from '@kit.BasicServicesKit';
3227  import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit';
3228  // move directory from srcPath to destPath
3229  let srcPath = pathDir + "/srcDir/";
3230  let destPath = pathDir + "/destDir/";
3231  fs.moveDir(srcPath, destPath, 1, (err: BusinessError<Array<ConflictFiles>>) => {
3232    if (err && err.code == 13900015 && err.data?.length !== undefined) {
3233      for (let i = 0; i < err.data.length; i++) {
3234        console.error("move directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile);
3235      }
3236    } else if (err) {
3237      console.error("move directory failed with error message: " + err.message + ", error code: " + err.code);
3238    } else {
3239      console.info("move directory succeed");
3240    }
3241  });
3242  ```
3243
3244  ## fs.moveDir<sup>10+</sup>
3245
3246moveDir(src: string, dest: string, callback: AsyncCallback\<void, Array\<ConflictFiles>>): void
3247
3248移动源文件夹至目标路径下。使用callback异步回调。
3249
3250移动模式为文件夹级别抛异常,当目标文件夹下存在与源文件夹名冲突的文件夹,则抛出异常。
3251
3252> **说明:**
3253> 该接口不支持在分布式文件路径下操作。
3254
3255**系统能力**:SystemCapability.FileManagement.File.FileIO
3256
3257**参数:**
3258
3259  | 参数名    | 类型     | 必填   | 说明                          |
3260  | ------ | ------ | ---- | --------------------------- |
3261  | src | string | 是    | 源文件夹的应用沙箱路径。 |
3262  | dest | string | 是    | 目标文件夹的应用沙箱路径。 |
3263  | callback | AsyncCallback&lt;void, Array&lt;[ConflictFiles](#conflictfiles10)&gt;&gt; | 是    | 异步移动文件夹之后的回调。              |
3264
3265**错误码:**
3266
3267接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3268
3269**示例:**
3270
3271  ```ts
3272  import { BusinessError } from '@kit.BasicServicesKit';
3273  import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit';
3274  // move directory from srcPath to destPath
3275  let srcPath = pathDir + "/srcDir/";
3276  let destPath = pathDir + "/destDir/";
3277  fs.moveDir(srcPath, destPath, (err: BusinessError<Array<ConflictFiles>>) => {
3278    if (err && err.code == 13900015 && err.data?.length !== undefined) {
3279      for (let i = 0; i < err.data.length; i++) {
3280        console.error("move directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile);
3281      }
3282    } else if (err) {
3283      console.error("move directory failed with error message: " + err.message + ", error code: " + err.code);
3284    } else {
3285      console.info("move directory succeed");
3286    }
3287  });
3288  ```
3289
3290## fs.moveDirSync<sup>10+</sup>
3291
3292moveDirSync(src: string, dest: string, mode?: number): void
3293
3294以同步方法移动源文件夹至目标路径下。
3295
3296> **说明:**
3297> 该接口不支持在分布式文件路径下操作。
3298
3299**系统能力**:SystemCapability.FileManagement.File.FileIO
3300
3301**参数:**
3302
3303  | 参数名    | 类型     | 必填   | 说明                          |
3304  | ------ | ------ | ---- | --------------------------- |
3305  | src | string | 是    | 源文件夹的应用沙箱路径。 |
3306  | dest | string | 是    | 目标文件夹的应用沙箱路径。 |
3307  | mode | number | 否    | 移动模式。默认mode为0。<br/>-&nbsp;mode为0,文件夹级别抛异常。若目标文件夹下存在与源文件夹名冲突的文件夹,则抛出异常。<br/>-&nbsp;mode为1,文件级别抛异常。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则抛出异常。源文件夹下未冲突的文件全部移动至目标文件夹下,目标文件夹下未冲突文件将继续保留,且冲突文件信息将在抛出异常的data属性中以Array\<[ConflictFiles](#conflictfiles10)>形式提供。<br/>-&nbsp; mode为2,文件级别强制覆盖。目标文件夹下存在与源文件夹名冲突的文件夹,若冲突文件夹下存在同名文件,则强制覆盖冲突文件夹下所有同名文件,未冲突文件将继续保留。<br/>-&nbsp; mode为3,文件夹级别强制覆盖。移动源文件夹至目标文件夹下,目标文件夹下移动的文件夹内容与源文件夹完全一致。若目标文件夹下存在与源文件夹名冲突的文件夹,该文件夹下所有原始文件将不会保留。|
3308
3309**错误码:**
3310
3311接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3312
3313**示例:**
3314
3315  ```ts
3316  import { BusinessError } from '@kit.BasicServicesKit';
3317import { fileIo as fs, ConflictFiles } from '@kit.CoreFileKit';
3318// move directory from srcPath to destPath
3319let srcPath = pathDir + "/srcDir/";
3320let destPath = pathDir + "/destDir/";
3321try {
3322  fs.moveDirSync(srcPath, destPath, 1);
3323  console.info("move directory succeed");
3324} catch (error) {
3325  let err: BusinessError<Array<ConflictFiles>> = error as BusinessError<Array<ConflictFiles>>;
3326  if (err.code == 13900015 && err.data?.length !== undefined) {
3327    for (let i = 0; i < err.data.length; i++) {
3328      console.error("move directory failed with conflicting files: " + err.data[i].srcFile + " " + err.data[i].destFile);
3329    }
3330  } else {
3331    console.error("move directory failed with error message: " + err.message + ", error code: " + err.code);
3332  }
3333}
3334  ```
3335
3336## fs.moveFile
3337
3338moveFile(src: string, dest: string, mode?: number): Promise\<void>
3339
3340移动文件,使用Promise异步返回。
3341
3342> **说明:**
3343> 该接口不支持在分布式文件路径下操作。
3344
3345**系统能力**:SystemCapability.FileManagement.File.FileIO
3346
3347**参数:**
3348
3349  | 参数名    | 类型     | 必填   | 说明                          |
3350  | ------ | ------ | ---- | --------------------------- |
3351  | src | string | 是    | 源文件的应用沙箱路径。 |
3352  | dest | string | 是    | 目的文件的应用沙箱路径。 |
3353  | mode | number | 否    | 移动模式。若mode为0,移动位置存在同名文件时,强制移动覆盖。若mode为1,移动位置存在同名文件时,抛出异常。默认为0。 |
3354
3355**返回值:**
3356
3357  | 类型                  | 说明                           |
3358  | ------------------- | ---------------------------- |
3359  | Promise&lt;void&gt; | Promise对象。无返回值。 |
3360
3361**错误码:**
3362
3363接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3364
3365**示例:**
3366
3367  ```ts
3368  import { BusinessError } from '@kit.BasicServicesKit';
3369  let srcPath = pathDir + "/source.txt";
3370  let destPath = pathDir + "/dest.txt";
3371  fs.moveFile(srcPath, destPath, 0).then(() => {
3372    console.info("move file succeed");
3373  }).catch((err: BusinessError) => {
3374    console.error("move file failed with error message: " + err.message + ", error code: " + err.code);
3375  });
3376  ```
3377
3378## fs.moveFile
3379
3380moveFile(src: string, dest: string, mode: number, callback: AsyncCallback\<void>): void
3381
3382移动文件,支持设置移动模式。使用callback异步回调。
3383
3384> **说明:**
3385> 该接口不支持在分布式文件路径下操作。
3386
3387**系统能力**:SystemCapability.FileManagement.File.FileIO
3388
3389**参数:**
3390
3391  | 参数名    | 类型     | 必填   | 说明                          |
3392  | ------ | ------ | ---- | --------------------------- |
3393  | src | string | 是    | 源文件的应用沙箱路径。 |
3394  | dest | string | 是    | 目的文件的应用沙箱路径。 |
3395  | mode | number | 是    | 移动模式。若mode为0,移动位置存在同名文件时,强制移动覆盖。若mode为1,移动位置存在同名文件时,抛出异常。默认为0。 |
3396  | callback | AsyncCallback&lt;void&gt; | 是    | 异步移动文件之后的回调。              |
3397
3398**错误码:**
3399
3400接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3401
3402**示例:**
3403
3404  ```ts
3405  import { BusinessError } from '@kit.BasicServicesKit';
3406  let srcPath = pathDir + "/source.txt";
3407  let destPath = pathDir + "/dest.txt";
3408  fs.moveFile(srcPath, destPath, 0, (err: BusinessError) => {
3409    if (err) {
3410      console.error("move file failed with error message: " + err.message + ", error code: " + err.code);
3411    } else {
3412      console.info("move file succeed");
3413    }
3414  });
3415  ```
3416
3417## fs.moveFile
3418
3419moveFile(src: string, dest: string, callback: AsyncCallback\<void>): void
3420
3421移动文件,当移动位置存在同名文件时,将强制移动覆盖。使用callback异步回调。
3422
3423> **说明:**
3424> 该接口不支持在分布式文件路径下操作。
3425
3426**系统能力**:SystemCapability.FileManagement.File.FileIO
3427
3428**参数:**
3429
3430  | 参数名    | 类型     | 必填   | 说明                          |
3431  | ------ | ------ | ---- | --------------------------- |
3432  | src | string | 是    | 源文件的应用沙箱路径。 |
3433  | dest | string | 是    | 目的文件的应用沙箱路径。 |
3434  | callback | AsyncCallback&lt;void&gt; | 是    | 异步移动文件之后的回调。 |
3435
3436**错误码:**
3437
3438接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3439
3440**示例:**
3441
3442  ```ts
3443  import { BusinessError } from '@kit.BasicServicesKit';
3444  let srcPath = pathDir + "/source.txt";
3445  let destPath = pathDir + "/dest.txt";
3446  fs.moveFile(srcPath, destPath, (err: BusinessError) => {
3447    if (err) {
3448      console.error("move file failed with error message: " + err.message + ", error code: " + err.code);
3449    } else {
3450      console.info("move file succeed");
3451    }
3452  });
3453  ```
3454
3455## fs.moveFileSync
3456
3457moveFileSync(src: string, dest: string, mode?: number): void
3458
3459以同步方式移动文件。
3460
3461> **说明:**
3462> 该接口不支持在分布式文件路径下操作。
3463
3464**系统能力**:SystemCapability.FileManagement.File.FileIO
3465
3466**参数:**
3467
3468  | 参数名    | 类型     | 必填   | 说明                          |
3469  | ------ | ------ | ---- | --------------------------- |
3470  | src | string | 是    | 源文件的应用沙箱路径。 |
3471  | dest | string | 是    | 目的文件的应用沙箱路径。 |
3472  | mode | number | 否    | 移动模式。若mode为0,移动位置存在同名文件时,强制移动覆盖。若mode为1,移动位置存在同名文件时,抛出异常。默认为0。 |
3473
3474**错误码:**
3475
3476接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3477
3478**示例:**
3479
3480  ```ts
3481  let srcPath = pathDir + "/source.txt";
3482  let destPath = pathDir + "/dest.txt";
3483  fs.moveFileSync(srcPath, destPath, 0);
3484  console.info("move file succeed");
3485  ```
3486
3487## fs.mkdtemp
3488
3489mkdtemp(prefix: string): Promise&lt;string&gt;
3490
3491创建临时目录,使用Promise异步返回。
3492
3493**系统能力**:SystemCapability.FileManagement.File.FileIO
3494
3495**参数:**
3496
3497  | 参数名    | 类型     | 必填   | 说明                          |
3498  | ------ | ------ | ---- | --------------------------- |
3499  | prefix | string | 是    | 指定目录路径,命名时需要以"XXXXXX"作为结尾。路径末尾的"XXXXXX"字符串将被替换为随机字符,以创建唯一的目录名。 |
3500
3501**返回值:**
3502
3503  | 类型                   | 说明         |
3504  | --------------------- | ---------- |
3505  | Promise&lt;string&gt; | Promise对象。返回生成的唯一目录路径。 |
3506
3507**错误码:**
3508
3509接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3510
3511**示例:**
3512
3513  ```ts
3514  import { BusinessError } from '@kit.BasicServicesKit';
3515  fs.mkdtemp(pathDir + "/XXXXXX").then((dir: string) => {
3516    console.info("mkdtemp succeed:" + dir);
3517  }).catch((err: BusinessError) => {
3518    console.error("mkdtemp failed with error message: " + err.message + ", error code: " + err.code);
3519  });
3520  ```
3521
3522## fs.mkdtemp
3523
3524mkdtemp(prefix: string, callback: AsyncCallback&lt;string&gt;): void
3525
3526创建临时目录,使用callback异步回调。
3527
3528**系统能力**:SystemCapability.FileManagement.File.FileIO
3529
3530**参数:**
3531
3532  | 参数名      | 类型                          | 必填   | 说明                          |
3533  | -------- | --------------------------- | ---- | --------------------------- |
3534  | prefix   | string                      | 是    | 指定目录路径,命名时需要以"XXXXXX"作为结尾。路径末尾的"XXXXXX"字符串将被替换为随机字符,以创建唯一的目录名。 |
3535  | callback | AsyncCallback&lt;string&gt; | 是    | 异步创建临时目录之后的回调。              |
3536
3537**错误码:**
3538
3539接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3540
3541**示例:**
3542
3543  ```ts
3544  import { BusinessError } from '@kit.BasicServicesKit';
3545  fs.mkdtemp(pathDir + "/XXXXXX", (err: BusinessError, res: string) => {
3546    if (err) {
3547      console.error("mkdtemp failed with error message: " + err.message + ", error code: " + err.code);
3548    } else {
3549      console.info("mkdtemp succeed");
3550    }
3551  });
3552  ```
3553
3554## fs.mkdtempSync
3555
3556mkdtempSync(prefix: string): string
3557
3558以同步的方法创建临时目录。
3559
3560**系统能力**:SystemCapability.FileManagement.File.FileIO
3561
3562**参数:**
3563
3564  | 参数名    | 类型     | 必填   | 说明                          |
3565  | ------ | ------ | ---- | --------------------------- |
3566  | prefix | string | 是    | 指定目录路径,命名时需要以"XXXXXX"作为结尾。路径末尾的"XXXXXX"字符串将被替换为随机字符,以创建唯一的目录名。 |
3567
3568**返回值:**
3569
3570  | 类型    | 说明         |
3571  | ------ | ---------- |
3572  | string | 产生的唯一目录路径。 |
3573
3574**错误码:**
3575
3576接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3577
3578**示例:**
3579
3580  ```ts
3581  let res = fs.mkdtempSync(pathDir + "/XXXXXX");
3582  ```
3583
3584## fs.utimes<sup>11+</sup>
3585
3586utimes(path: string, mtime: number): void
3587
3588修改文件最近访问时间属性。
3589
3590**系统能力**:SystemCapability.FileManagement.File.FileIO
3591
3592**参数:**
3593|    参数名    | 类型     | 必填   | 说明                          |
3594| ------------ | ------ | ------ | ------------------------------------------------------------ |
3595| path  | string  |  是    | 文件的应用沙箱路径。 |
3596| mtime  | number  |  是   | 待更新的时间戳。自1970年1月1日起至目标时间的毫秒数。仅支持修改文件最近访问时间属性。 |
3597
3598**错误码:**
3599
3600接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3601
3602**示例:**
3603
3604  ```ts
3605  let filePath = pathDir + "/test.txt";
3606  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
3607  fs.writeSync(file.fd, 'test data');
3608  fs.closeSync(file);
3609  fs.utimes(filePath, new Date().getTime());
3610  ```
3611
3612## fs.createRandomAccessFile<sup>10+</sup>
3613
3614createRandomAccessFile(file: string | File, mode?: number): Promise&lt;RandomAccessFile&gt;
3615
3616基于文件路径或文件对象创建RandomAccessFile文件对象,使用Promise异步返回。
3617
3618**系统能力**:SystemCapability.FileManagement.File.FileIO
3619
3620**参数:**
3621|    参数名    | 类型     | 必填   | 说明                          |
3622| ------------ | ------ | ------ | ------------------------------------------------------------ |
3623|     file     | string \| [File](#file) | 是    | 文件的应用沙箱路径或已打开的File对象 |
3624|     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对象。 |
3625
3626**返回值:**
3627
3628  | 类型                                | 说明        |
3629  | --------------------------------- | --------- |
3630  | Promise&lt;[RandomAccessFile](#randomaccessfile)&gt; | Promise对象。返回RandomAccessFile文件对象的结果。 |
3631
3632**错误码:**
3633
3634接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3635
3636**示例:**
3637
3638  ```ts
3639  import { BusinessError } from '@kit.BasicServicesKit';
3640  let filePath = pathDir + "/test.txt";
3641  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
3642  fs.createRandomAccessFile(file).then((randomAccessFile: fs.RandomAccessFile) => {
3643    console.info("randomAccessFile fd: " + randomAccessFile.fd);
3644    randomAccessFile.close();
3645  }).catch((err: BusinessError) => {
3646    console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
3647  }).finally(() => {
3648    fs.closeSync(file);
3649  });
3650  ```
3651
3652## fs.createRandomAccessFile<sup>10+</sup>
3653
3654createRandomAccessFile(file: string | File, callback: AsyncCallback&lt;RandomAccessFile&gt;): void
3655
3656基于文件路径或文件对象,以只读方式创建RandomAccessFile文件对象,使用callback异步回调。
3657
3658**系统能力**:SystemCapability.FileManagement.File.FileIO
3659
3660**参数:**
3661
3662|  参数名    | 类型     | 必填   | 说明                          |
3663| ------------ | ------ | ------ | ------------------------------------------------------------ |
3664|     file     | string \| [File](#file) | 是    | 文件的应用沙箱路径或已打开的File对象 |
3665| callback | AsyncCallback&lt;[RandomAccessFile](#randomaccessfile)&gt; | 是   | 异步创建RandomAccessFile对象之后的回调。                                   |
3666
3667**错误码:**
3668
3669接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3670
3671**示例:**
3672  ```ts
3673  import { BusinessError } from '@kit.BasicServicesKit';
3674  let filePath = pathDir + "/test.txt";
3675  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
3676  fs.createRandomAccessFile(file, (err: BusinessError, randomAccessFile: fs.RandomAccessFile) => {
3677    if (err) {
3678      console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
3679    } else {
3680      console.info("randomAccessFile fd: " + randomAccessFile.fd);
3681      randomAccessFile.close();
3682    }
3683    fs.closeSync(file);
3684  });
3685  ```
3686
3687  ## fs.createRandomAccessFile<sup>10+</sup>
3688
3689createRandomAccessFile(file: string | File, mode: number, callback: AsyncCallback&lt;RandomAccessFile&gt;): void
3690
3691基于文件路径或文件对象创建RandomAccessFile文件对象。使用callback异步回调。
3692
3693**系统能力**:SystemCapability.FileManagement.File.FileIO
3694
3695**参数:**
3696
3697|  参数名    | 类型     | 必填   | 说明                          |
3698| ------------ | ------ | ------ | ------------------------------------------------------------ |
3699|     file     | string \| [File](#file) | 是    | 文件的应用沙箱路径或已打开的File对象 |
3700|     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对象。 |
3701| callback | AsyncCallback&lt;[RandomAccessFile](#randomaccessfile)&gt; | 是   | 异步创建RandomAccessFile对象之后的回调。                                   |
3702
3703**错误码:**
3704
3705接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3706
3707**示例:**
3708  ```ts
3709  import { BusinessError } from '@kit.BasicServicesKit';
3710  let filePath = pathDir + "/test.txt";
3711  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
3712  fs.createRandomAccessFile(file, fs.OpenMode.READ_ONLY, (err: BusinessError, randomAccessFile: fs.RandomAccessFile) => {
3713    if (err) {
3714      console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
3715    } else {
3716      console.info("randomAccessFile fd: " + randomAccessFile.fd);
3717      randomAccessFile.close();
3718    }
3719    fs.closeSync(file);
3720  });
3721  ```
3722
3723## fs.createRandomAccessFile<sup>12+</sup>
3724
3725createRandomAccessFile(file: string | File, mode?: number, options?: RandomAccessFileOptions): Promise&lt;RandomAccessFile&gt;
3726
3727基于文件路径或文件对象创建RandomAccessFile文件对象。使用Promise异步返回。
3728
3729**系统能力**:SystemCapability.FileManagement.File.FileIO
3730
3731**参数:**
3732
3733|  参数名    | 类型     | 必填   | 说明                          |
3734| ------------ | ------ | ------ | ------------------------------------------------------------ |
3735|     file     | string \| [File](#file) | 是    | 文件的应用沙箱路径或已打开的File对象 |
3736|     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对象。 |
3737|options|[RandomAccessFileOptions](#randomaccessfileoptions12)|否|支持如下选项:<br/>- start,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- end,number类型,表示期望读取结束的位置。可选,默认文件末尾。|
3738
3739**返回值:**
3740
3741  | 类型                                | 说明        |
3742  | --------------------------------- | --------- |
3743  | Promise&lt;[RandomAccessFile](#randomaccessfile)&gt; | Promise对象。返回RandomAccessFile文件对象的结果。 |
3744
3745**错误码:**
3746
3747接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3748
3749```ts
3750import { BusinessError } from '@kit.BasicServicesKit';
3751let filePath = pathDir + "/test.txt";
3752fs.createRandomAccessFile(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE, { start: 10, end: 100 })
3753  .then((randomAccessFile: fs.RandomAccessFile) => {
3754    console.info("randomAccessFile fd: " + randomAccessFile.fd);
3755    randomAccessFile.close();
3756  })
3757  .catch((err: BusinessError) => {
3758    console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
3759  });
3760```
3761
3762
3763## fs.createRandomAccessFileSync<sup>10+</sup>
3764
3765createRandomAccessFileSync(file: string | File, mode?: number): RandomAccessFile
3766
3767基于文件路径或文件对象创建RandomAccessFile文件对象。
3768
3769**系统能力**:SystemCapability.FileManagement.File.FileIO
3770
3771**参数:**
3772
3773|  参数名    | 类型     | 必填   | 说明                          |
3774| ------------ | ------ | ------ | ------------------------------------------------------------ |
3775|     file     | string \| [File](#file) | 是    | 文件的应用沙箱路径或已打开的File对象 |
3776|     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对象。 |
3777
3778**返回值:**
3779
3780  | 类型                | 说明        |
3781  | ------------------ | --------- |
3782  | [RandomAccessFile](#randomaccessfile) | 返回RandomAccessFile文件对象。 |
3783
3784**错误码:**
3785
3786接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3787
3788**示例:**
3789
3790  ```ts
3791  let filePath = pathDir + "/test.txt";
3792  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
3793  let randomAccessFile = fs.createRandomAccessFileSync(file);
3794  randomAccessFile.close();
3795  ```
3796
3797## fs.createRandomAccessFileSync<sup>12+</sup>
3798
3799createRandomAccessFileSync(file: string | File, mode?: number,
3800  options?: RandomAccessFileOptions): RandomAccessFile;
3801
3802基于文件路径或文件对象创建RandomAccessFile文件对象。
3803
3804**系统能力**:SystemCapability.FileManagement.File.FileIO
3805
3806**参数:**
3807
3808|  参数名    | 类型     | 必填   | 说明                          |
3809| ------------ | ------ | ------ | ------------------------------------------------------------ |
3810|     file     | string \| [File](#file) | 是    | 文件的应用沙箱路径或已打开的File对象 |
3811|     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对象。 |
3812|options|[RandomAccessFileOptions](#randomaccessfileoptions12)|否|支持如下选项:<br/>- start,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- end,number类型,表示期望读取结束的位置。可选,默认文件末尾。|
3813
3814**返回值:**
3815
3816  | 类型                | 说明        |
3817  | ------------------ | --------- |
3818  | [RandomAccessFile](#randomaccessfile) | 返回RandomAccessFile文件对象。 |
3819
3820**错误码:**
3821
3822接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3823
3824**示例:**
3825
3826  ```ts
3827  let filePath = pathDir + "/test.txt";
3828  let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE,
3829    { start: 10, end: 100 });
3830  randomAccessFile.close();
3831  ```
3832
3833## fs.createStream
3834
3835createStream(path: string, mode: string): Promise&lt;Stream&gt;
3836
3837基于文件路径创建文件流,使用Promise异步返回。需要配合[Stream](#stream)中的close()函数关闭文件流。
3838
3839**系统能力**:SystemCapability.FileManagement.File.FileIO
3840
3841**参数:**
3842
3843| 参数名 | 类型   | 必填 | 说明                                                         |
3844| ------ | ------ | ---- | ------------------------------------------------------------ |
3845| path   | string | 是   | 文件的应用沙箱路径。                                   |
3846| mode   | string | 是   | -&nbsp;r:打开只读文件,该文件必须存在。<br/>-&nbsp;r+:打开可读写的文件,该文件必须存在。<br/>-&nbsp;w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>-&nbsp;a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 |
3847
3848**返回值:**
3849
3850  | 类型                                | 说明        |
3851  | --------------------------------- | --------- |
3852  | Promise&lt;[Stream](#stream)&gt; | Promise对象。返回文件流的结果。 |
3853
3854**错误码:**
3855
3856接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3857
3858**示例:**
3859
3860  ```ts
3861  import { BusinessError } from '@kit.BasicServicesKit';
3862  let filePath = pathDir + "/test.txt";
3863  fs.createStream(filePath, "a+").then((stream: fs.Stream) => {
3864    stream.closeSync();
3865    console.info("createStream succeed");
3866  }).catch((err: BusinessError) => {
3867    console.error("createStream failed with error message: " + err.message + ", error code: " + err.code);
3868  });
3869  ```
3870
3871
3872## fs.createStream
3873
3874createStream(path: string, mode: string, callback: AsyncCallback&lt;Stream&gt;): void
3875
3876基于文件路径创建文件流,使用callback异步回调。需要配合[Stream](#stream)中的close()函数关闭文件流。
3877
3878**系统能力**:SystemCapability.FileManagement.File.FileIO
3879
3880**参数:**
3881
3882| 参数名   | 类型                                    | 必填 | 说明                                                         |
3883| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
3884| path     | string                                  | 是   | 文件的应用沙箱路径。                                   |
3885| mode     | string                                  | 是   | -&nbsp;r:打开只读文件,该文件必须存在。<br/>-&nbsp;r+:打开可读写的文件,该文件必须存在。<br/>-&nbsp;w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>-&nbsp;a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 |
3886| callback | AsyncCallback&lt;[Stream](#stream)&gt; | 是   | 异步打开文件流之后的回调。                                   |
3887
3888**错误码:**
3889
3890接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3891
3892**示例:**
3893
3894  ```ts
3895  import { BusinessError } from '@kit.BasicServicesKit';
3896  let filePath = pathDir + "/test.txt";
3897  fs.createStream(filePath, "r+", (err: BusinessError, stream: fs.Stream) => {
3898    if (err) {
3899      console.error("create stream failed with error message: " + err.message + ", error code: " + err.code);
3900    } else {
3901      console.info("createStream succeed");
3902    }
3903    stream.closeSync();
3904  })
3905  ```
3906
3907## fs.createStreamSync
3908
3909createStreamSync(path: string, mode: string): Stream
3910
3911以同步方法基于文件路径创建文件流。需要配合[Stream](#stream)中的close()函数关闭文件流。
3912
3913**系统能力**:SystemCapability.FileManagement.File.FileIO
3914
3915**参数:**
3916
3917| 参数名 | 类型   | 必填 | 说明                                                         |
3918| ------ | ------ | ---- | ------------------------------------------------------------ |
3919| path   | string | 是   | 文件的应用沙箱路径。                                   |
3920| mode   | string | 是   | -&nbsp;r:打开只读文件,该文件必须存在。<br/>-&nbsp;r+:打开可读写的文件,该文件必须存在。<br/>-&nbsp;w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>-&nbsp;a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 |
3921
3922**返回值:**
3923
3924  | 类型                | 说明        |
3925  | ------------------ | --------- |
3926  | [Stream](#stream) | 返回文件流的结果。 |
3927
3928**错误码:**
3929
3930接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3931
3932**示例:**
3933
3934  ```ts
3935  let filePath = pathDir + "/test.txt";
3936  let stream = fs.createStreamSync(filePath, "r+");
3937  console.info("createStream succeed");
3938  stream.closeSync();
3939  ```
3940
3941
3942## fs.fdopenStream
3943
3944fdopenStream(fd: number, mode: string): Promise&lt;Stream&gt;
3945
3946基于文件描述符打开文件流,使用Promise异步返回。需要配合[Stream](#stream)中的close()函数关闭文件流。
3947
3948**系统能力**:SystemCapability.FileManagement.File.FileIO
3949
3950**参数:**
3951
3952  | 参数名  | 类型     | 必填   | 说明                                       |
3953  | ---- | ------ | ---- | ---------------------------------------- |
3954  | fd   | number | 是    | 已打开的文件描述符。                             |
3955  | mode | string | 是    | -&nbsp;r:打开只读文件,该文件必须存在。<br/>-&nbsp;r+:打开可读写的文件,该文件必须存在。<br/>-&nbsp;w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>-&nbsp;a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 |
3956
3957**返回值:**
3958
3959  | 类型                               | 说明        |
3960  | --------------------------------- | --------- |
3961  | Promise&lt;[Stream](#stream)&gt; | Promise对象。返回文件流的结果。 |
3962
3963**错误码:**
3964
3965接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
3966
3967**示例:**
3968
3969  ```ts
3970  import { BusinessError } from '@kit.BasicServicesKit';
3971  let filePath = pathDir + "/test.txt";
3972  let file = fs.openSync(filePath);
3973  fs.fdopenStream(file.fd, "r+").then((stream: fs.Stream) => {
3974    console.info("openStream succeed");
3975    stream.closeSync();
3976  }).catch((err: BusinessError) => {
3977    console.error("openStream failed with error message: " + err.message + ", error code: " + err.code);
3978    // 文件流打开失败后,文件描述符需要手动关闭
3979    fs.closeSync(file);
3980  });
3981  ```
3982
3983> **注意:**
3984>
3985> 使用文件描述符创建的文件流,文件描述符的生命周期也交由文件流对象,在调用文件流的close()函数后,初始的文件描述符也会被关闭。
3986
3987## fs.fdopenStream
3988
3989fdopenStream(fd: number, mode: string, callback: AsyncCallback&lt;Stream&gt;): void
3990
3991基于文件描述符打开文件流,使用callback异步回调。需要配合[Stream](#stream)中的close()函数关闭文件流。
3992
3993**系统能力**:SystemCapability.FileManagement.File.FileIO
3994
3995**参数:**
3996
3997  | 参数名      | 类型                                       | 必填   | 说明                                       |
3998  | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
3999  | fd       | number                                   | 是    | 已打开的文件描述符。                             |
4000  | mode     | string                                   | 是    | -&nbsp;r:打开只读文件,该文件必须存在。<br/>-&nbsp;r+:打开可读写的文件,该文件必须存在。<br/>-&nbsp;w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>-&nbsp;a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 |
4001  | callback | AsyncCallback&lt;[Stream](#stream)&gt; | 是    | 异步打开文件流之后的回调。                            |
4002
4003**错误码:**
4004
4005接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4006
4007**示例:**
4008
4009  ```ts
4010  import { BusinessError } from '@kit.BasicServicesKit';
4011  let filePath = pathDir + "/test.txt";
4012  let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
4013  fs.fdopenStream(file.fd, "r+", (err: BusinessError, stream: fs.Stream) => {
4014    if (err) {
4015      console.error("fdopen stream failed with error message: " + err.message + ", error code: " + err.code);
4016      stream.closeSync();
4017    } else {
4018      console.info("fdopen stream succeed");
4019      // 文件流打开失败后,文件描述符需要手动关闭
4020      fs.closeSync(file);
4021    }
4022  });
4023  ```
4024
4025> **注意:**
4026>
4027> 使用文件描述符创建的文件流,文件描述符的生命周期也交由文件流对象,在调用文件流的close()函数后,初始的文件描述符也会被关闭。
4028
4029## fs.fdopenStreamSync
4030
4031fdopenStreamSync(fd: number, mode: string): Stream
4032
4033以同步方法基于文件描述符打开文件流。需要配合[Stream](#stream)中的close()函数关闭文件流。
4034
4035**系统能力**:SystemCapability.FileManagement.File.FileIO
4036
4037**参数:**
4038
4039  | 参数名  | 类型     | 必填   | 说明                                       |
4040  | ---- | ------ | ---- | ---------------------------------------- |
4041  | fd   | number | 是    | 已打开的文件描述符。                             |
4042  | mode | string | 是    | -&nbsp;r:打开只读文件,该文件必须存在。<br/>-&nbsp;r+:打开可读写的文件,该文件必须存在。<br/>-&nbsp;w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。<br/>-&nbsp;a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。<br/>-&nbsp;a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 |
4043
4044**返回值:**
4045
4046  | 类型                | 说明        |
4047  | ------------------ | --------- |
4048  | [Stream](#stream) | 返回文件流的结果。 |
4049
4050**错误码:**
4051
4052接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4053
4054**示例:**
4055
4056  ```ts
4057  let filePath = pathDir + "/test.txt";
4058  let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE);
4059  let stream = fs.fdopenStreamSync(file.fd, "r+");
4060  stream.closeSync();
4061  ```
4062
4063> **注意:**
4064>
4065> 使用文件描述符创建的文件流,文件描述符的生命周期也交由文件流对象,在调用文件流的close()函数后,初始的文件描述符也会被关闭。
4066
4067## fs.createReadStream<sup>12+</sup>
4068
4069createReadStream(path: string, options?: ReadStreamOptions ): ReadStream;
4070
4071以同步方法打开文件可读流。
4072
4073**系统能力**:SystemCapability.FileManagement.File.FileIO
4074
4075**参数:**
4076
4077  | 参数名  | 类型     | 必填   | 说明                                       |
4078  | ---- | ------ | ---- | ---------------------------------------- |
4079  | path   | string | 是    | 文件路径                             |
4080  | options | [ReadStreamOptions](#readstreamoptions12) | 否    | 支持如下选项:<br/>- start,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>- end,number类型,表示期望读取结束的位置。可选,默认文件末尾。 |
4081
4082**返回值:**
4083
4084  | 类型                | 说明        |
4085  | ------------------ | --------- |
4086  | [ReadStream](#readstream12) | 文件可读流 |
4087
4088**错误码:**
4089
4090接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4091
4092**示例:**
4093
4094  ```ts
4095 // 创建文件可读流
4096  const rs = fs.createReadStream(`${pathDir}/read.txt`);
4097  // 创建文件可写流
4098  const ws = fs.createWriteStream(`${pathDir}/write.txt`);
4099  // 暂停模式拷贝文件
4100  rs.on('readable', () => {
4101    const data = rs.read();
4102    if (!data) {
4103      return;
4104    }
4105    ws.write(data);
4106  });
4107  ```
4108
4109## fs.createWriteStream<sup>12+</sup>
4110
4111createWriteStream(path: string, options?: WriteStreamOptions): WriteStream;
4112
4113以同步方法打开文件可写流。
4114
4115**系统能力**:SystemCapability.FileManagement.File.FileIO
4116
4117**参数:**
4118
4119  | 参数名  | 类型     | 必填   | 说明                                       |
4120  | ---- | ------ | ---- | ---------------------------------------- |
4121  | path   | string | 是    | 文件路径                             |
4122  | options | [WriteStreamOptions](#writestreamoptions12) | 否    | 支持如下选项:<br/>- start,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>- mode,number 类型,创建文件可写流的[选项](#openmode),可选,默认以只写方式创建。 |
4123
4124**返回值:**
4125
4126  | 类型                | 说明        |
4127  | ------------------ | --------- |
4128  | [WriteStream](#writestream12) | 文件可写流 |
4129
4130**错误码:**
4131
4132接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4133
4134**示例:**
4135
4136  ```ts
4137 // 创建文件可读流
4138  const rs = fs.createReadStream(`${pathDir}/read.txt`);
4139  // 创建文件可写流
4140  const ws = fs.createWriteStream(`${pathDir}/write.txt`);
4141  // 暂停模式拷贝文件
4142  rs.on('readable', () => {
4143    const data = rs.read();
4144    if (!data) {
4145      return;
4146    }
4147    ws.write(data);
4148  });
4149  ```
4150
4151## fs.createWatcher<sup>10+</sup>
4152
4153createWatcher(path: string, events: number, listener: WatchEventListener): Watcher
4154
4155创建Watcher对象,用来监听文件或目录变动。
4156
4157**系统能力**:SystemCapability.FileManagement.File.FileIO
4158
4159**参数:**
4160
4161  | 参数名  | 类型     | 必填   | 说明                                       |
4162  | ---- | ------ | ---- | ---------------------------------------- |
4163  | path   | string | 是    | 监听文件或目录的沙箱路径。                             |
4164  | 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,监听以上所有事件。|
4165  | listener   | [WatchEventListener](#watcheventlistener10) | 是    | 监听事件发生后的回调。监听事件每发生一次,回调一次。                             |
4166
4167**返回值:**
4168
4169  | 类型                | 说明        |
4170  | ------------------ | --------- |
4171  | [Watcher](#watcher10) | 返回Watcher对象。 |
4172
4173**错误码:**
4174
4175接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4176
4177**示例:**
4178
4179  ```ts
4180  import { fileIo as fs, WatchEvent } from '@kit.CoreFileKit';
4181  let filePath = pathDir + "/test.txt";
4182  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
4183  let watcher = fs.createWatcher(filePath, 0x2 | 0x10, (watchEvent: WatchEvent) => {
4184    if (watchEvent.event == 0x2) {
4185      console.info(watchEvent.fileName + 'was modified');
4186    } else if (watchEvent.event == 0x10) {
4187      console.info(watchEvent.fileName + 'was closed');
4188    }
4189  });
4190  watcher.start();
4191  fs.writeSync(file.fd, 'test');
4192  fs.closeSync(file);
4193  watcher.stop();
4194  ```
4195
4196## WatchEventListener<sup>10+</sup>
4197
4198(event: WatchEvent): void
4199
4200事件监听类。
4201
4202**系统能力**:SystemCapability.FileManagement.File.FileIO
4203
4204**参数:**
4205
4206  | 参数名  | 类型     | 必填   | 说明                                       |
4207  | ---- | ------ | ---- | ---------------------------------------- |
4208  | event   | [WatchEvent](#watchevent10) | 是    | 回调的事件类。                             |
4209
4210## WatchEvent<sup>10+</sup>
4211
4212事件类
4213
4214**系统能力**:SystemCapability.FileManagement.File.FileIO
4215
4216### 属性
4217
4218| 名称   | 类型   | 只读   | 可写   | 说明      |
4219| ---- | ------ | ---- | ---- | ------- |
4220| fileName | string | 是    | 否    | 发生监听事件对应文件的沙箱路径,该沙箱路径包含文件名称。 |
4221| 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,监听以上所有事件。 |
4222| cookie | number | 是    | 否    | 绑定相关事件的cookie。当前仅支持事件IN_MOVED_FROM与IN_MOVED_TO,同一个文件的移动事件IN_MOVED_FROM和IN_MOVED_TO具有相同的cookie值。 |
4223
4224## Progress<sup>11+</sup>
4225
4226拷贝进度回调数据
4227
4228**系统能力**:SystemCapability.FileManagement.File.FileIO
4229
4230| 名称   | 类型   | 只读   | 可写   | 说明      |
4231| ---- | ------ | ---- | ---- | ------- |
4232| processedSize | number | 是    | 否    | 已拷贝的数据大小。 |
4233| totalSize | number | 是    | 否    | 待拷贝的数据总大小。 |
4234
4235## TaskSignal<sup>12+</sup>
4236
4237拷贝中断信号。
4238
4239**系统能力**:SystemCapability.FileManagement.File.FileIO
4240
4241### cancel<sup>12+</sup>
4242
4243cancel(): void
4244
4245取消拷贝任务。
4246
4247**系统能力**:SystemCapability.FileManagement.File.FileIO
4248
4249**错误码:**
4250
4251接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4252
4253**示例:**
4254
4255```ts
4256import { BusinessError } from '@kit.BasicServicesKit';
4257import { fileIo as fs } from '@kit.CoreFileKit';
4258import { fileUri } from '@kit.CoreFileKit';
4259import common from '@ohos.app.ability.common';
4260let context = getContext(this) as common.UIAbilityContext;
4261let pathDir: string = context.filesDir;
4262let srcDirPathLocal: string = pathDir + "/src";
4263let dstDirPathLocal: string = pathDir + "/dest";
4264let srcDirUriLocal: string = fileUri.getUriFromPath(srcDirPathLocal);
4265let dstDirUriLocal: string = fileUri.getUriFromPath(dstDirPathLocal);
4266let copySignal = new fs.TaskSignal;
4267let progressListener: fs.ProgressListener = (progress: fs.Progress) => {
4268  console.info(`progressSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`);
4269  if (progress.processedSize / progress.totalSize > 0.5) {
4270    copySignal.cancel();
4271  }
4272};
4273let options: fs.CopyOptions = {
4274  "progressListener" : progressListener,
4275  "copySignal" : new fs.TaskSignal,
4276}
4277console.info("copyFileWithCancel success.");
4278try {
4279  fs.copy(srcDirPathLocal, dstDirUriLocal, options, (err: BusinessError) => {
4280    if (err) {
4281      console.info("copyFileWithCancel fail.");
4282      return;
4283    }
4284    console.info("copyFileWithCancel success.");
4285  })
4286} catch (err) {
4287  console.error("copyFileWithCancel failed with invalid param.");
4288}
4289
4290```
4291
4292### onCancel<sup>12+</sup>
4293
4294onCancel(): Promise&lt;string&gt;
4295
4296取消拷贝事件监听。
4297
4298**系统能力**:SystemCapability.FileManagement.File.FileIO
4299
4300**返回值:**
4301
4302  | 类型                   | 说明         |
4303  | --------------------- | ---------- |
4304  | Promise&lt;string&gt; | Promise对象。最后一个拷贝的文件路径。 |
4305
4306**错误码:**
4307
4308接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4309
4310**示例:**
4311
4312```ts
4313import { fileIo as fs } from '@kit.CoreFileKit';
4314import { TaskSignal } from '@ohos.file.fs';
4315let copySignal: fs.TaskSignal = new TaskSignal();
4316copySignal.onCancel().then(() => {
4317    console.info("copyFileWithCancel success.");
4318});
4319```
4320
4321## CopyOptions<sup>11+</sup>
4322
4323拷贝进度回调监听
4324
4325**系统能力**:SystemCapability.FileManagement.File.FileIO
4326
4327| 名称   | 类型   | 可读   | 可写   | 说明      |
4328| ---- | ------ | ---- | ---- | ------- |
4329| progressListener | [ProgressListener](#progresslistener11) | 是    | 是    | 拷贝进度监听。 |
4330| copySignal | [TaskSignal](#tasksignal12) | 是    | 是    | 取消拷贝信号。 |
4331
4332## ProgressListener<sup>11+</sup>
4333
4334拷贝进度监听。
4335
4336**系统能力**:SystemCapability.FileManagement.File.FileIO
4337
4338| 类型 | 说明 |
4339| ----| ------|
4340|(progress: [Progress](#progress11)) => void| 拷贝进度监听|
4341
4342**示例:**
4343
4344  ```ts
4345  let copySignal: fs.TaskSignal = new TaskSignal();
4346  let progressListener: fs.ProgressListener = (progress: fs.Progress) => {
4347    console.info(`processedSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`);
4348  };
4349  let copyOption: fs.CopyOptions = {
4350    "progressListener" : progressListener,
4351    "copySignal" : copySignal,
4352  }
4353  ```
4354
4355## Stat
4356
4357文件具体信息,在调用Stat的方法前,需要先通过[stat()](#fsstat)方法(同步或异步)来构建一个Stat实例。
4358
4359**系统能力**:SystemCapability.FileManagement.File.FileIO
4360
4361### 属性
4362
4363| 名称     | 类型   | 只读   | 可写   | 说明                                       |
4364| ------ | ------ | ---- | ---- | ---------------------------------------- |
4365| ino    | bigint | 是    | 否    | 标识该文件。通常同设备上的不同文件的INO不同。|                 |
4366| 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开始,该接口支持在原子化服务中使用。 |
4367| uid    | number | 是    | 否    | 文件所有者的ID。|
4368| gid    | number | 是    | 否    | 文件所有组的ID。|
4369| size   | number | 是    | 否    | 文件的大小,以字节为单位。仅对普通文件有效。 <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
4370| atime  | number | 是    | 否    | 上次访问该文件的时间,表示距1970年1月1日0时0分0秒的秒数。  <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。      |
4371| mtime  | number | 是    | 否    | 上次修改该文件的时间,表示距1970年1月1日0时0分0秒的秒数。  <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。      |
4372| ctime  | number | 是    | 否    | 最近改变文件状态的时间,表示距1970年1月1日0时0分0秒的秒数。      |
4373| location<sup>11+</sup> | [LocaltionType](#locationtype11)| 是 |否| 文件的位置,表示该文件是本地文件或者云端文件。
4374
4375### isBlockDevice
4376
4377isBlockDevice(): boolean
4378
4379用于判断文件是否是块特殊文件。一个块特殊文件只能以块为粒度进行访问,且访问的时候带缓存。
4380
4381**系统能力**:SystemCapability.FileManagement.File.FileIO
4382
4383**返回值:**
4384
4385  | 类型     | 说明               |
4386  | ------- | ---------------- |
4387  | boolean | 表示文件是否是块特殊设备。 |
4388
4389**错误码:**
4390
4391接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4392
4393**示例:**
4394
4395  ```ts
4396  let filePath = pathDir + "/test.txt";
4397  let isBLockDevice = fs.statSync(filePath).isBlockDevice();
4398  ```
4399
4400### isCharacterDevice
4401
4402isCharacterDevice(): boolean
4403
4404用于判断文件是否是字符特殊文件。一个字符特殊设备可进行随机访问,且访问的时候不带缓存。
4405
4406**系统能力**:SystemCapability.FileManagement.File.FileIO
4407
4408**返回值:**
4409
4410  | 类型      | 说明                |
4411  | ------- | ----------------- |
4412  | boolean | 表示文件是否是字符特殊设备。 |
4413
4414**错误码:**
4415
4416接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4417
4418**示例:**
4419
4420  ```ts
4421  let filePath = pathDir + "/test.txt";
4422  let isCharacterDevice = fs.statSync(filePath).isCharacterDevice();
4423  ```
4424
4425### isDirectory
4426
4427isDirectory(): boolean
4428
4429用于判断文件是否是目录。
4430
4431**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
4432
4433**系统能力**:SystemCapability.FileManagement.File.FileIO
4434
4435**返回值:**
4436
4437  | 类型      | 说明            |
4438  | ------- | ------------- |
4439  | boolean | 表示文件是否是目录。 |
4440
4441**错误码:**
4442
4443接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4444
4445**示例:**
4446
4447  ```ts
4448  let dirPath = pathDir + "/test";
4449  let isDirectory = fs.statSync(dirPath).isDirectory();
4450  ```
4451
4452### isFIFO
4453
4454isFIFO(): boolean
4455
4456用于判断文件是否是命名管道(有时也称为FIFO)。命名管道通常用于进程间通信。
4457
4458**系统能力**:SystemCapability.FileManagement.File.FileIO
4459
4460**返回值:**
4461
4462  | 类型      | 说明                    |
4463  | ------- | --------------------- |
4464  | boolean | 表示文件是否是&nbsp;FIFO。 |
4465
4466**错误码:**
4467
4468接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4469
4470**示例:**
4471
4472  ```ts
4473  let filePath = pathDir + "/test.txt";
4474  let isFIFO = fs.statSync(filePath).isFIFO();
4475  ```
4476
4477### isFile
4478
4479isFile(): boolean
4480
4481用于判断文件是否是普通文件。
4482
4483**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
4484
4485**系统能力**:SystemCapability.FileManagement.File.FileIO
4486
4487**返回值:**
4488
4489  | 类型      | 说明              |
4490  | ------- | --------------- |
4491  | boolean | 表示文件是否是普通文件。 |
4492
4493**错误码:**
4494
4495接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4496
4497**示例:**
4498
4499  ```ts
4500  let filePath = pathDir + "/test.txt";
4501  let isFile = fs.statSync(filePath).isFile();
4502  ```
4503
4504### isSocket
4505
4506isSocket(): boolean
4507
4508用于判断文件是否是套接字。
4509
4510**系统能力**:SystemCapability.FileManagement.File.FileIO
4511
4512**返回值:**
4513
4514  | 类型      | 说明             |
4515  | ------- | -------------- |
4516  | boolean | 表示文件是否是套接字。 |
4517
4518**错误码:**
4519
4520接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4521
4522**示例:**
4523
4524  ```ts
4525  let filePath = pathDir + "/test.txt";
4526  let isSocket = fs.statSync(filePath).isSocket();
4527  ```
4528
4529### isSymbolicLink
4530
4531isSymbolicLink(): boolean
4532
4533用于判断文件是否是符号链接。
4534
4535**系统能力**:SystemCapability.FileManagement.File.FileIO
4536
4537**返回值:**
4538
4539  | 类型      | 说明              |
4540  | ------- | --------------- |
4541  | boolean | 表示文件是否是符号链接。 |
4542
4543**错误码:**
4544
4545接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4546
4547**示例:**
4548
4549  ```ts
4550  let filePath = pathDir + "/test";
4551  let isSymbolicLink = fs.statSync(filePath).isSymbolicLink();
4552  ```
4553
4554## Stream
4555
4556文件流,在调用Stream的方法前,需要先通过[fs.createStream](#fscreatestream)方法或者[fs.fdopenStream](#fsfdopenstream)(同步或异步)来构建一个Stream实例。
4557
4558### close
4559
4560close(): Promise&lt;void&gt;
4561
4562关闭文件流,使用Promise异步返回。
4563
4564**系统能力**:SystemCapability.FileManagement.File.FileIO
4565
4566**返回值:**
4567
4568  | 类型                  | 说明            |
4569  | ------------------- | ------------- |
4570  | Promise&lt;void&gt; | Promise对象。无返回值。 |
4571
4572**错误码:**
4573
4574接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4575
4576**示例:**
4577
4578  ```ts
4579  import { BusinessError } from '@kit.BasicServicesKit';
4580  let filePath = pathDir + "/test.txt";
4581  let stream = fs.createStreamSync(filePath, "r+");
4582  stream.close().then(() => {
4583    console.info("close fileStream succeed");
4584  }).catch((err: BusinessError) => {
4585    console.error("close fileStream  failed with error message: " + err.message + ", error code: " + err.code);
4586  });
4587  ```
4588
4589### close
4590
4591close(callback: AsyncCallback&lt;void&gt;): void
4592
4593异步关闭文件流,使用callback异步回调。
4594
4595**系统能力**:SystemCapability.FileManagement.File.FileIO
4596
4597**参数:**
4598
4599  | 参数名      | 类型                        | 必填   | 说明            |
4600  | -------- | ------------------------- | ---- | ------------- |
4601  | callback | AsyncCallback&lt;void&gt; | 是    | 异步关闭文件流之后的回调。 |
4602
4603**错误码:**
4604
4605接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4606
4607**示例:**
4608
4609  ```ts
4610  import { BusinessError } from '@kit.BasicServicesKit';
4611  let filePath = pathDir + "/test.txt";
4612  let stream = fs.createStreamSync(filePath, "r+");
4613  stream.close((err: BusinessError) => {
4614    if (err) {
4615      console.error("close stream failed with error message: " + err.message + ", error code: " + err.code);
4616    } else {
4617      console.info("close stream succeed");
4618    }
4619  });
4620  ```
4621
4622### closeSync
4623
4624closeSync(): void
4625
4626同步关闭文件流。
4627
4628**系统能力**:SystemCapability.FileManagement.File.FileIO
4629
4630**错误码:**
4631
4632接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4633
4634**示例:**
4635
4636  ```ts
4637  let filePath = pathDir + "/test.txt";
4638  let stream = fs.createStreamSync(filePath, "r+");
4639  stream.closeSync();
4640  ```
4641
4642### flush
4643
4644flush(): Promise&lt;void&gt;
4645
4646刷新文件流,使用Promise异步返回。
4647
4648**系统能力**:SystemCapability.FileManagement.File.FileIO
4649
4650**返回值:**
4651
4652  | 类型                  | 说明            |
4653  | ------------------- | ------------- |
4654  | Promise&lt;void&gt; | Promise对象。返回表示异步刷新文件流的结果。 |
4655
4656**错误码:**
4657
4658接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4659
4660**示例:**
4661
4662  ```ts
4663  import { BusinessError } from '@kit.BasicServicesKit';
4664  let filePath = pathDir + "/test.txt";
4665  let stream = fs.createStreamSync(filePath, "r+");
4666  stream.flush().then(() => {
4667    console.info("flush succeed");
4668    stream.close();
4669  }).catch((err: BusinessError) => {
4670    console.error("flush failed with error message: " + err.message + ", error code: " + err.code);
4671  });
4672  ```
4673
4674### flush
4675
4676flush(callback: AsyncCallback&lt;void&gt;): void
4677
4678异步刷新文件流,使用callback异步回调。
4679
4680**系统能力**:SystemCapability.FileManagement.File.FileIO
4681
4682**参数:**
4683
4684  | 参数名      | 类型                        | 必填   | 说明             |
4685  | -------- | ------------------------- | ---- | -------------- |
4686  | callback | AsyncCallback&lt;void&gt; | 是    | 异步刷新文件流后的回调函数。 |
4687
4688**错误码:**
4689
4690接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4691
4692**示例:**
4693
4694  ```ts
4695  import { BusinessError } from '@kit.BasicServicesKit';
4696  let filePath = pathDir + "/test.txt";
4697  let stream = fs.createStreamSync(filePath, "r+");
4698  stream.flush((err: BusinessError) => {
4699    if (err) {
4700      console.error("flush stream failed with error message: " + err.message + ", error code: " + err.code);
4701    } else {
4702      console.info("flush succeed");
4703      stream.close();
4704    }
4705  });
4706  ```
4707
4708### flushSync
4709
4710flushSync(): void
4711
4712同步刷新文件流。
4713
4714**系统能力**:SystemCapability.FileManagement.File.FileIO
4715
4716**错误码:**
4717
4718接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4719
4720**示例:**
4721
4722  ```ts
4723  let filePath = pathDir + "/test.txt";
4724  let stream = fs.createStreamSync(filePath, "r+");
4725  stream.flushSync();
4726  stream.close();
4727  ```
4728
4729### write
4730
4731write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise&lt;number&gt;
4732
4733将数据写入流文件,使用Promise异步返回。
4734
4735**系统能力**:SystemCapability.FileManagement.File.FileIO
4736
4737**参数:**
4738
4739  | 参数名     | 类型                              | 必填   | 说明                                       |
4740  | ------- | ------------------------------- | ---- | ---------------------------------------- |
4741  | buffer  | ArrayBuffer \| string | 是    | 待写入文件的数据,可来自缓冲区或字符串。                     |
4742  | options | [WriteOptions](#writeoptions11)                          | 否    | 支持如下选项:<br/>-&nbsp;length,number类型,表示期望写入数据的长度。默认缓冲区长度。<br/>-&nbsp;offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>-&nbsp;encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认&nbsp;'utf-8'。仅支持&nbsp;'utf-8'。|
4743
4744**返回值:**
4745
4746  | 类型                    | 说明       |
4747  | --------------------- | -------- |
4748  | Promise&lt;number&gt; | Promise对象。返回实际写入的长度。 |
4749
4750**错误码:**
4751
4752接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4753
4754**示例:**
4755
4756  ```ts
4757  import { BusinessError } from '@kit.BasicServicesKit';
4758  import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit';
4759  let filePath = pathDir + "/test.txt";
4760  let stream = fs.createStreamSync(filePath, "r+");
4761  let writeOption: WriteOptions = {
4762    offset: 5,
4763    length: 5,
4764    encoding: 'utf-8'
4765  };
4766  stream.write("hello, world", writeOption).then((number: number) => {
4767    console.info("write succeed and size is:" + number);
4768    stream.close();
4769  }).catch((err: BusinessError) => {
4770    console.error("write failed with error message: " + err.message + ", error code: " + err.code);
4771  });
4772  ```
4773
4774### write
4775
4776write(buffer: ArrayBuffer | string, options?: WriteOptions, callback: AsyncCallback&lt;number&gt;): void
4777
4778将数据写入流文件,使用callback异步回调。
4779
4780**系统能力**:SystemCapability.FileManagement.File.FileIO
4781
4782**参数:**
4783
4784  | 参数名   | 类型                            | 必填 | 说明                                                         |
4785  | -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
4786  | buffer   | ArrayBuffer \| string | 是   | 待写入文件的数据,可来自缓冲区或字符串。                     |
4787  | options  | [WriteOptions](#writeoptions11)                          | 否   | 支持如下选项:<br/>-&nbsp;length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>-&nbsp;offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>-&nbsp;encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认&nbsp;'utf-8'。仅支持&nbsp;'utf-8'。|
4788  | callback | AsyncCallback&lt;number&gt;     | 是   | 异步写入完成后执行的回调函数。                               |
4789
4790**错误码:**
4791
4792接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4793
4794**示例:**
4795
4796  ```ts
4797  import { BusinessError } from '@kit.BasicServicesKit';
4798  import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit';
4799  let filePath = pathDir + "/test.txt";
4800  let stream = fs.createStreamSync(filePath, "r+");
4801  let writeOption: WriteOptions = {
4802    offset: 5,
4803    length: 5,
4804    encoding: 'utf-8'
4805  };
4806  stream.write("hello, world", writeOption, (err: BusinessError, bytesWritten: number) => {
4807    if (err) {
4808      console.error("write stream failed with error message: " + err.message + ", error code: " + err.code);
4809    } else {
4810      if (bytesWritten) {
4811        console.info("write succeed and size is:" + bytesWritten);
4812        stream.close();
4813      }
4814    }
4815  });
4816  ```
4817
4818### writeSync
4819
4820writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number
4821
4822以同步方法将数据写入流文件。
4823
4824**系统能力**:SystemCapability.FileManagement.File.FileIO
4825
4826**参数:**
4827
4828  | 参数名     | 类型                              | 必填   | 说明                                       |
4829  | ------- | ------------------------------- | ---- | ---------------------------------------- |
4830  | buffer  | ArrayBuffer \| string | 是    | 待写入文件的数据,可来自缓冲区或字符串。                     |
4831  | options | [WriteOptions](#writeoptions11)                          | 否    | 支持如下选项:<br/>-&nbsp;length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度。<br/>-&nbsp;offset,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。<br/>-&nbsp;encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认&nbsp;'utf-8'。仅支持&nbsp;'utf-8'。|
4832
4833**返回值:**
4834
4835  | 类型     | 说明       |
4836  | ------ | -------- |
4837  | number | 实际写入的长度。 |
4838
4839**错误码:**
4840
4841接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4842
4843**示例:**
4844
4845  ```ts
4846  import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit';
4847  let filePath = pathDir + "/test.txt";
4848  let stream = fs.createStreamSync(filePath,"r+");
4849  let writeOption: WriteOptions = {
4850    offset: 5,
4851    length: 5,
4852    encoding: 'utf-8'
4853  };
4854  let num = stream.writeSync("hello, world", writeOption);
4855  stream.close();
4856  ```
4857
4858### read
4859
4860read(buffer: ArrayBuffer, options?: ReadOptions): Promise&lt;number&gt;
4861
4862从流文件读取数据,使用Promise异步返回。
4863
4864**系统能力**:SystemCapability.FileManagement.File.FileIO
4865
4866**参数:**
4867
4868  | 参数名     | 类型          | 必填   | 说明                                       |
4869  | ------- | ----------- | ---- | ---------------------------------------- |
4870  | buffer  | ArrayBuffer | 是    | 用于读取文件的缓冲区。                              |
4871  | options | [ReadOptions](#readoptions11)      | 否    | 支持如下选项:<br/>-&nbsp;length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>-&nbsp;offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。 |
4872
4873**返回值:**
4874
4875  | 类型                                 | 说明     |
4876  | ---------------------------------- | ------ |
4877  | Promise&lt;number&gt; | Promise对象。返回读取的结果。 |
4878
4879**错误码:**
4880
4881接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4882
4883**示例:**
4884
4885  ```ts
4886  import { BusinessError } from '@kit.BasicServicesKit';
4887  import { buffer } from '@kit.ArkTS';
4888  import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
4889  let filePath = pathDir + "/test.txt";
4890  let stream = fs.createStreamSync(filePath, "r+");
4891  let arrayBuffer = new ArrayBuffer(4096);
4892  let readOption: ReadOptions = {
4893    offset: 5,
4894    length: 5
4895  };
4896  stream.read(arrayBuffer, readOption).then((readLen: number) => {
4897    console.info("read data succeed");
4898    let buf = buffer.from(arrayBuffer, 0, readLen);
4899    console.log(`The content of file: ${buf.toString()}`);
4900    stream.close();
4901  }).catch((err: BusinessError) => {
4902    console.error("read data failed with error message: " + err.message + ", error code: " + err.code);
4903  });
4904  ```
4905
4906### read
4907
4908read(buffer: ArrayBuffer, options?: ReadOptions, callback: AsyncCallback&lt;number&gt;): void
4909
4910从流文件读取数据,使用callback异步回调。
4911
4912**系统能力**:SystemCapability.FileManagement.File.FileIO
4913
4914**参数:**
4915
4916  | 参数名      | 类型                                       | 必填   | 说明                                       |
4917  | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
4918  | buffer   | ArrayBuffer                              | 是    | 用于读取文件的缓冲区。                              |
4919  | options  | [ReadOptions](#readoptions11)                                   | 否    | 支持如下选项:<br/>-&nbsp;length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>-&nbsp;offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读. |
4920  | callback | AsyncCallback&lt;number&gt; | 是    | 异步从流文件读取数据之后的回调。                         |
4921
4922**错误码:**
4923
4924接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4925
4926**示例:**
4927
4928  ```ts
4929  import { BusinessError } from '@kit.BasicServicesKit';
4930  import { buffer } from '@kit.ArkTS';
4931  import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
4932  let filePath = pathDir + "/test.txt";
4933  let stream = fs.createStreamSync(filePath, "r+");
4934  let arrayBuffer = new ArrayBuffer(4096);
4935  let readOption: ReadOptions = {
4936    offset: 5,
4937    length: 5
4938  };
4939  stream.read(arrayBuffer, readOption, (err: BusinessError, readLen: number) => {
4940    if (err) {
4941      console.error("read stream failed with error message: " + err.message + ", error code: " + err.code);
4942    } else {
4943      console.info("read data succeed");
4944      let buf = buffer.from(arrayBuffer, 0, readLen);
4945      console.log(`The content of file: ${buf.toString()}`);
4946      stream.close();
4947    }
4948  });
4949  ```
4950
4951### readSync
4952
4953readSync(buffer: ArrayBuffer, options?: ReadOptions): number
4954
4955以同步方法从流文件读取数据。
4956
4957**系统能力**:SystemCapability.FileManagement.File.FileIO
4958
4959**参数:**
4960
4961  | 参数名     | 类型          | 必填   | 说明                                       |
4962  | ------- | ----------- | ---- | ---------------------------------------- |
4963  | buffer  | ArrayBuffer | 是    | 用于读取文件的缓冲区。                              |
4964  | options | [ReadOptions](#readoptions11)      | 否    | 支持如下选项:<br/>-&nbsp;length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>-&nbsp;offset,number类型,表示期望读取文件的位置。可选,默认从当前位置开始读。<br/>  |
4965
4966**返回值:**
4967
4968  | 类型     | 说明       |
4969  | ------ | -------- |
4970  | number | 实际读取的长度。 |
4971
4972**错误码:**
4973
4974接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
4975
4976**示例:**
4977
4978  ```ts
4979  import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
4980  let filePath = pathDir + "/test.txt";
4981  let stream = fs.createStreamSync(filePath, "r+");
4982  let readOption: ReadOptions = {
4983    offset: 5,
4984    length: 5
4985  };
4986  let buf = new ArrayBuffer(4096);
4987  let num = stream.readSync(buf, readOption);
4988  stream.close();
4989  ```
4990
4991## File
4992
4993由open接口打开的File对象。
4994
4995**系统能力**:SystemCapability.FileManagement.File.FileIO
4996
4997### 属性
4998
4999| 名称   | 类型   | 只读   | 可写   | 说明      |
5000| ---- | ------ | ---- | ---- | ------- |
5001| fd | number | 是    | 否    | 打开的文件描述符。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
5002| path<sup>10+</sup> | string | 是    | 否    | 文件路径。 |
5003| name<sup>10+</sup> | string | 是    | 否    | 文件名。 |
5004
5005### getParent<sup>11+</sup>
5006
5007getParent(): string
5008
5009获取File对象对应文件父目录。
5010
5011**系统能力**:SystemCapability.FileManagement.File.FileIO
5012
5013**返回值:**
5014
5015  | 类型                                 | 说明     |
5016  | ---------------------------------- | ------ |
5017  | string | 返回父目录路径。 |
5018
5019**错误码:**
5020
5021接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5022
5023**示例:**
5024
5025  ```ts
5026  import { BusinessError } from '@kit.BasicServicesKit';
5027  let filePath = pathDir + "/test.txt";
5028  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
5029  console.info('The parent path is: ' + file.getParent());
5030  fs.closeSync(file);
5031  ```
5032
5033### lock
5034
5035lock(exclusive?: boolean): Promise\<void>
5036
5037文件阻塞式施加共享锁或独占锁,使用Promise异步返回。
5038
5039**系统能力**:SystemCapability.FileManagement.File.FileIO
5040
5041**参数:**
5042
5043  | 参数名     | 类型          | 必填   | 说明                                       |
5044  | ------- | ----------- | ---- | ---------------------------------------- |
5045  | exclusive  | boolean | 否   | 是否施加独占锁,默认false。       |
5046
5047**返回值:**
5048
5049  | 类型                                 | 说明     |
5050  | ---------------------------------- | ------ |
5051  | Promise&lt;void&gt; | Promise对象。无返回值。 |
5052
5053**错误码:**
5054
5055接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5056
5057**示例:**
5058
5059  ```ts
5060  import { BusinessError } from '@kit.BasicServicesKit';
5061  let filePath = pathDir + "/test.txt";
5062  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
5063  file.lock(true).then(() => {
5064    console.log("lock file succeed");
5065  }).catch((err: BusinessError) => {
5066    console.error("lock file failed with error message: " + err.message + ", error code: " + err.code);
5067  }).finally(() => {
5068    fs.closeSync(file);
5069  });
5070  ```
5071
5072### lock
5073
5074lock(exclusive?: boolean, callback: AsyncCallback\<void>): void
5075
5076文件阻塞式施加共享锁或独占锁,使Callback异步回调。
5077
5078**系统能力**:SystemCapability.FileManagement.File.FileIO
5079
5080**参数:**
5081
5082  | 参数名     | 类型          | 必填   | 说明                                       |
5083  | ------- | ----------- | ---- | ---------------------------------------- |
5084  | exclusive  | boolean | 否   | 是否施加独占锁,默认false。       |
5085  | callback | AsyncCallback&lt;void&gt; | 是    | 异步文件上锁之后的回调。   |
5086
5087**错误码:**
5088
5089接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5090
5091**示例:**
5092
5093  ```ts
5094  import { BusinessError } from '@kit.BasicServicesKit';
5095  let filePath = pathDir + "/test.txt";
5096  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
5097  file.lock(true, (err: BusinessError) => {
5098    if (err) {
5099      console.error("lock file failed with error message: " + err.message + ", error code: " + err.code);
5100    } else {
5101      console.log("lock file succeed");
5102    }
5103    fs.closeSync(file);
5104  });
5105  ```
5106
5107### tryLock
5108
5109tryLock(exclusive?: boolean): void
5110
5111文件非阻塞式施加共享锁或独占锁。
5112
5113**系统能力**:SystemCapability.FileManagement.File.FileIO
5114
5115**参数:**
5116
5117  | 参数名     | 类型          | 必填   | 说明                                       |
5118  | ------- | ----------- | ---- | ---------------------------------------- |
5119  | exclusive  | boolean | 否   | 是否施加独占锁,默认false。       |
5120
5121**错误码:**
5122
5123接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5124
5125**示例:**
5126
5127  ```ts
5128  let filePath = pathDir + "/test.txt";
5129  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
5130  file.tryLock(true);
5131  console.log("lock file succeed");
5132  fs.closeSync(file);
5133  ```
5134
5135### unlock
5136
5137unlock(): void
5138
5139以同步方式给文件解锁。
5140
5141**系统能力**:SystemCapability.FileManagement.File.FileIO
5142
5143**错误码:**
5144
5145接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5146
5147**示例:**
5148
5149  ```ts
5150  let filePath = pathDir + "/test.txt";
5151  let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
5152  file.tryLock(true);
5153  file.unlock();
5154  console.log("unlock file succeed");
5155  fs.closeSync(file);
5156  ```
5157
5158  ## fs.DfsListeners<sup>12+</sup>
5159
5160interface DfsListeners {
5161  onStatus(networkId: string, status: number): void;
5162}
5163
5164事件监听类。创建DFSListener对象,用于监听分布式文件系统状态。
5165
5166**系统能力**:SystemCapability.FileManagement.File.FileIO
5167
5168### onStatus<sup>12+</sup>
5169
5170onStatus(networkId: string, status: number): void;
5171
5172事件回调类。参数由[connectDfs](#fsconnectdfs12)传入。
5173
5174**系统能力**:SystemCapability.FileManagement.File.FileIO
5175
5176**参数:**
5177
5178  | 参数名  | 类型     | 必填   | 说明                              |
5179  | ---- | ------ | ---- | ---------------------------------------- |
5180  | networkId   | string | 是    | 设备的网络Id。                             |
5181  | status | number | 是    | 分布式文件系统的状态码(以connectDfs回调onStatus的特定错误码作为入参)。触发场景为connectDfs调用过程中出现对端设备异常,对应错误码为:<br/>-&nbsp;[13900046](errorcode-filemanagement.md#13900046):软件造成连接中断。
5182
5183## RandomAccessFile
5184
5185随机读写文件流,在调用RandomAccessFile的方法前,需要先通过createRandomAccess()方法(同步或异步)来构建一个RandomAccessFile实例。
5186
5187**系统能力**:SystemCapability.FileManagement.File.FileIO
5188
5189### 属性
5190
5191| 名称         | 类型   | 只读  | 可写  | 说明              |
5192| ----------- | ------ | ----  | ----- | ---------------- |
5193| fd          | number | 是    | 否    | 打开的文件描述符。 |
5194| filePointer | number | 是    | 是    | RandomAccessFile对象的偏置指针。 |
5195
5196### setFilePointer<sup>10+</sup>
5197
5198setFilePointer(): void
5199
5200设置文件偏置指针
5201
5202**系统能力**:SystemCapability.FileManagement.File.FileIO
5203
5204**错误码:**
5205
5206接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5207
5208**示例:**
5209
5210  ```ts
5211  let filePath = pathDir + "/test.txt";
5212  let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
5213  randomAccessFile.setFilePointer(1);
5214  randomAccessFile.close();
5215  ```
5216
5217
5218### close<sup>10+</sup>
5219
5220close(): void
5221
5222同步关闭RandomAccessFile对象。
5223
5224**系统能力**:SystemCapability.FileManagement.File.FileIO
5225
5226**错误码:**
5227
5228接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5229
5230**示例:**
5231
5232  ```ts
5233  let filePath = pathDir + "/test.txt";
5234  let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
5235  randomAccessFile.close();
5236  ```
5237
5238### write<sup>10+</sup>
5239
5240write(buffer: ArrayBuffer | string, options?: WriteOptions): Promise&lt;number&gt;
5241
5242将数据写入文件,使用Promise异步返回。
5243
5244**系统能力**:SystemCapability.FileManagement.File.FileIO
5245
5246**参数:**
5247
5248  | 参数名     | 类型                              | 必填   | 说明                                       |
5249  | ------- | ------------------------------- | ---- | ---------------------------------------- |
5250  | buffer  | ArrayBuffer \| string | 是    | 待写入文件的数据,可来自缓冲区或字符串。                     |
5251  | 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'。|
5252
5253**返回值:**
5254
5255  | 类型                    | 说明       |
5256  | --------------------- | -------- |
5257  | Promise&lt;number&gt; | Promise对象。返回实际写入的长度。 |
5258
5259**错误码:**
5260
5261接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5262
5263**示例:**
5264
5265  ```ts
5266  import { BusinessError } from '@kit.BasicServicesKit';
5267  import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit';
5268  let filePath = pathDir + "/test.txt";
5269  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
5270  let randomAccessFile = fs.createRandomAccessFileSync(file);
5271  let bufferLength: number = 4096;
5272  let writeOption: WriteOptions = {
5273    offset: 1,
5274    length: 5,
5275    encoding: 'utf-8'
5276  };
5277  let arrayBuffer = new ArrayBuffer(bufferLength);
5278  randomAccessFile.write(arrayBuffer, writeOption).then((bytesWritten: number) => {
5279    console.info("randomAccessFile bytesWritten: " + bytesWritten);
5280  }).catch((err: BusinessError) => {
5281    console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
5282  }).finally(() => {
5283    randomAccessFile.close();
5284    fs.closeSync(file);
5285  });
5286
5287  ```
5288
5289### write<sup>10+</sup>
5290
5291write(buffer: ArrayBuffer | string, options?: WriteOptions, callback: AsyncCallback&lt;number&gt;): void
5292
5293将数据写入文件,使用callback异步回调。
5294
5295**系统能力**:SystemCapability.FileManagement.File.FileIO
5296
5297**参数:**
5298
5299  | 参数名   | 类型                            | 必填 | 说明                                                         |
5300  | -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
5301  | buffer   | ArrayBuffer \| string | 是   | 待写入文件的数据,可来自缓冲区或字符串。                     |
5302  | 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'。|
5303  | callback | AsyncCallback&lt;number&gt;     | 是   | 异步写入完成后执行的回调函数。                               |
5304
5305**错误码:**
5306
5307接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5308
5309**示例:**
5310
5311  ```ts
5312  import { BusinessError } from '@kit.BasicServicesKit';
5313  import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit';
5314  let filePath = pathDir + "/test.txt";
5315  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
5316  let randomAccessFile = fs.createRandomAccessFileSync(file);
5317  let bufferLength: number = 4096;
5318  let writeOption: WriteOptions = {
5319    offset: 1,
5320    length: bufferLength,
5321    encoding: 'utf-8'
5322  };
5323  let arrayBuffer = new ArrayBuffer(bufferLength);
5324  randomAccessFile.write(arrayBuffer, writeOption, (err: BusinessError, bytesWritten: number) => {
5325    if (err) {
5326      console.error("write failed with error message: " + err.message + ", error code: " + err.code);
5327    } else {
5328      if (bytesWritten) {
5329        console.info("write succeed and size is:" + bytesWritten);
5330      }
5331    }
5332    randomAccessFile.close();
5333    fs.closeSync(file);
5334  });
5335  ```
5336
5337### writeSync<sup>10+</sup>
5338
5339writeSync(buffer: ArrayBuffer | string, options?: WriteOptions): number
5340
5341以同步方法将数据写入文件。
5342
5343**系统能力**:SystemCapability.FileManagement.File.FileIO
5344
5345**参数:**
5346
5347  | 参数名     | 类型                              | 必填   | 说明                                       |
5348  | ------- | ------------------------------- | ---- | ---------------------------------------- |
5349  | buffer  | ArrayBuffer \| string | 是    | 待写入文件的数据,可来自缓冲区或字符串。                     |
5350  | 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'。|
5351
5352**返回值:**
5353
5354  | 类型     | 说明       |
5355  | ------ | -------- |
5356  | number | 实际写入的长度。 |
5357
5358**错误码:**
5359
5360接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5361
5362**示例:**
5363
5364  ```ts
5365  import { fileIo as fs, WriteOptions } from '@kit.CoreFileKit';
5366  let filePath = pathDir + "/test.txt";
5367  let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
5368  let writeOption: WriteOptions = {
5369    offset: 5,
5370    length: 5,
5371    encoding: 'utf-8'
5372  };
5373  let bytesWritten = randomAccessFile.writeSync("hello, world", writeOption);
5374  randomAccessFile.close();
5375  ```
5376
5377### read<sup>10+</sup>
5378
5379read(buffer: ArrayBuffer, options?: ReadOptions): Promise&lt;number&gt;
5380
5381从文件读取数据,使用Promise异步返回。
5382
5383**系统能力**:SystemCapability.FileManagement.File.FileIO
5384
5385**参数:**
5386
5387  | 参数名     | 类型          | 必填   | 说明                                       |
5388  | ------- | ----------- | ---- | ---------------------------------------- |
5389  | buffer  | ArrayBuffer | 是    | 用于读取文件的缓冲区。                              |
5390  | options | [ReadOptions](#readoptions11)      | 否    | 支持如下选项:<br/>-&nbsp;length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>-&nbsp;offset,number类型,表示期望读取文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始读。 |
5391
5392**返回值:**
5393
5394  | 类型                                 | 说明     |
5395  | ---------------------------------- | ------ |
5396  | Promise&lt;number&gt; | Promise对象。返回读取的结果。 |
5397
5398**错误码:**
5399
5400接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5401
5402**示例:**
5403
5404  ```ts
5405  import { BusinessError } from '@kit.BasicServicesKit';
5406  import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
5407  let filePath = pathDir + "/test.txt";
5408  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
5409  let randomAccessFile = fs.createRandomAccessFileSync(file);
5410  let bufferLength: number = 4096;
5411  let readOption: ReadOptions = {
5412    offset: 1,
5413    length: 5
5414  };
5415  let arrayBuffer = new ArrayBuffer(bufferLength);
5416  randomAccessFile.read(arrayBuffer, readOption).then((readLength: number) => {
5417    console.info("randomAccessFile readLength: " + readLength);
5418  }).catch((err: BusinessError) => {
5419    console.error("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code);
5420  }).finally(() => {
5421    randomAccessFile.close();
5422    fs.closeSync(file);
5423  });
5424  ```
5425
5426### read<sup>10+</sup>
5427
5428read(buffer: ArrayBuffer, options?: ReadOptions, callback: AsyncCallback&lt;number&gt;): void
5429
5430从文件读取数据,使用callback异步回调。
5431
5432**系统能力**:SystemCapability.FileManagement.File.FileIO
5433
5434**参数:**
5435
5436  | 参数名      | 类型                                       | 必填   | 说明                                       |
5437  | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
5438  | buffer   | ArrayBuffer                              | 是    | 用于读取文件的缓冲区。                              |
5439  | options  | [ReadOptions](#readoptions11)                                   | 否    | 支持如下选项:<br/>-&nbsp;length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>-&nbsp;offset,number类型,表示期望读取文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始读. |
5440  | callback | AsyncCallback&lt;number&gt; | 是    | 异步从流文件读取数据之后的回调。                         |
5441
5442**错误码:**
5443
5444接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5445
5446**示例:**
5447
5448  ```ts
5449  import { BusinessError } from '@kit.BasicServicesKit';
5450  import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
5451  let filePath = pathDir + "/test.txt";
5452  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
5453  let randomAccessFile = fs.createRandomAccessFileSync(file);
5454  let length: number = 20;
5455  let readOption: ReadOptions = {
5456    offset: 1,
5457    length: 5
5458  };
5459  let arrayBuffer = new ArrayBuffer(length);
5460  randomAccessFile.read(arrayBuffer, readOption, (err: BusinessError, readLength: number) => {
5461    if (err) {
5462      console.error("read failed with error message: " + err.message + ", error code: " + err.code);
5463    } else {
5464      if (readLength) {
5465        console.info("read succeed and size is:" + readLength);
5466      }
5467    }
5468    randomAccessFile.close();
5469    fs.closeSync(file);
5470  });
5471  ```
5472
5473### readSync<sup>10+</sup>
5474
5475readSync(buffer: ArrayBuffer, options?: ReadOptions): number
5476
5477以同步方法从文件读取数据。
5478
5479**系统能力**:SystemCapability.FileManagement.File.FileIO
5480
5481**参数:**
5482
5483  | 参数名     | 类型          | 必填   | 说明                                       |
5484  | ------- | ----------- | ---- | ---------------------------------------- |
5485  | buffer  | ArrayBuffer | 是    | 用于读取文件的缓冲区。                              |
5486  | options | [ReadOptions](#readoptions11)      | 否    | 支持如下选项:<br/>-&nbsp;length,number类型,表示期望读取数据的长度。可选,默认缓冲区长度。<br/>-&nbsp;offset,number类型,表示期望读取文文件位置(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始读。<br/>  |
5487
5488**返回值:**
5489
5490  | 类型     | 说明       |
5491  | ------ | -------- |
5492  | number | 实际读取的长度。 |
5493
5494**错误码:**
5495
5496接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5497
5498**示例:**
5499
5500  ```ts
5501  let filePath = pathDir + "/test.txt";
5502  let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
5503  let randomAccessFile = fs.createRandomAccessFileSync(file);
5504  let length: number = 4096;
5505  let arrayBuffer = new ArrayBuffer(length);
5506  let readLength = randomAccessFile.readSync(arrayBuffer);
5507  randomAccessFile.close();
5508  fs.closeSync(file);
5509  ```
5510
5511### getReadStream<sup>12+</sup>
5512
5513getReadStream(): ReadStream;
5514
5515获取当前 RandomAccessFile 的一个 ReadStream 实例。
5516
5517**系统能力**:SystemCapability.FileManagement.File.FileIO
5518
5519**返回值:**
5520
5521  | 类型                | 说明        |
5522  | ------------------ | --------- |
5523  | [ReadStream](#readstream12) | 文件可读流 |
5524
5525**示例:**
5526
5527  ```ts
5528  const filePath = pathDir + "/test.txt";
5529  const randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
5530  const rs = randomAccessFile.getReadStream();
5531  rs.close();
5532  randomAccessFile.close();
5533  ```
5534
5535### getWriteStream<sup>12+</sup>
5536
5537getWriteStream(): WriteStream;
5538
5539获取当前 RandomAccessFile 的一个 WriteStream 实例。
5540
5541**系统能力**:SystemCapability.FileManagement.File.FileIO
5542
5543**返回值:**
5544
5545  | 类型                | 说明        |
5546  | ------------------ | --------- |
5547  | [WriteStream](#writestream12) | 文件可写流 |
5548
5549**示例:**
5550
5551  ```ts
5552  const filePath = pathDir + "/test.txt";
5553  const randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
5554  const ws = randomAccessFile.getWriteStream();
5555  ws.close();
5556  randomAccessFile.close();
5557  ```
5558
5559
5560## Watcher<sup>10+</sup>
5561
5562文件目录变化监听对象。由createWatcher接口获得。
5563
5564### start<sup>10+</sup>
5565
5566start(): void
5567
5568开启监听。
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 watcher = fs.createWatcher(filePath, 0xfff, () => {});
5581  watcher.start();
5582  watcher.stop();
5583  ```
5584
5585### stop<sup>10+</sup>
5586
5587stop(): void
5588
5589停止监听。
5590
5591**系统能力**:SystemCapability.FileManagement.File.FileIO
5592
5593**错误码:**
5594
5595接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5596
5597**示例:**
5598
5599  ```ts
5600  let filePath = pathDir + "/test.txt";
5601  let watcher = fs.createWatcher(filePath, 0xfff, () => {});
5602  watcher.start();
5603  watcher.stop();
5604  ```
5605
5606## OpenMode
5607
5608open接口flags参数常量。文件打开标签。
5609
5610**系统能力**:SystemCapability.FileManagement.File.FileIO
5611
5612| 名称   | 类型   | 值  | 说明      |
5613| ---- | ------ |---- | ------- |
5614| READ_ONLY | number |  0o0   | 只读打开。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
5615| WRITE_ONLY | number | 0o1    | 只写打开。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
5616| READ_WRITE | number | 0o2    | 读写打开。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
5617| CREATE | number | 0o100    | 若文件不存在,则创建文件。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
5618| TRUNC | number | 0o1000    | 如果文件存在且以只写或读写的方式打开文件,则将其长度裁剪为零。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
5619| APPEND | number | 0o2000   | 以追加方式打开,后续写将追加到文件末尾。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
5620| NONBLOCK | number | 0o4000    | 如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。 |
5621| DIR | number | 0o200000    | 如果path不指向目录,则出错。 |
5622| NOFOLLOW | number | 0o400000    | 如果path指向符号链接,则出错。 |
5623| SYNC | number | 0o4010000    | 以同步IO的方式打开文件。 |
5624
5625## Filter<sup>10+</sup>
5626
5627文件过滤配置项类型,支持listFile接口使用。
5628
5629**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
5630
5631**系统能力**:SystemCapability.FileManagement.File.FileIO
5632
5633| 名称        | 类型       | 必选       | 说明                |
5634| ----------- | --------------- | ------------------ | ------------------ |
5635| suffix | Array&lt;string&gt;     | 否 | 文件后缀名完全匹配,各个关键词OR关系。           |
5636| displayName    | Array&lt;string&gt;     | 否 | 文件名模糊匹配,各个关键词OR关系。当前仅支持通配符*。 |
5637| mimeType    | Array&lt;string&gt; | 否 | mime类型完全匹配,各个关键词OR关系。       |
5638| fileSizeOver    | number | 否 | 文件大小匹配,大于等于指定大小的文件。       |
5639| lastModifiedAfter    | number | 否 | 文件最近修改时间匹配,在指定时间点及之后的文件。       |
5640| excludeMedia    | boolean | 否 | 是否排除Media中已有的文件。       |
5641
5642## ConflictFiles<sup>10+</sup>
5643
5644冲突文件信息,支持copyDir及moveDir接口使用。
5645
5646**系统能力**:SystemCapability.FileManagement.File.FileIO
5647
5648| 名称        | 类型       | 说明                |
5649| ----------- | --------------- | ------------------ |
5650| srcFile | string     | 源冲突文件路径。           |
5651| destFile    | string     | 目标冲突文件路径。 |
5652
5653## Options<sup>11+</sup>
5654
5655可选项类型,支持readLines接口使用。
5656
5657**系统能力**:SystemCapability.FileManagement.File.FileIO
5658
5659| 名称        | 类型       | 说明                |
5660| ----------- | --------------- | ------------------ |
5661| encoding | string     | 文件编码方式。可选项。           |
5662
5663## WhenceType<sup>11+</sup>
5664
5665枚举,文件偏移指针相对偏移位置类型,支持lseek接口使用。
5666
5667**系统能力**:SystemCapability.FileManagement.File.FileIO
5668
5669| 名称        | 值       | 说明                |
5670| ----------- | --------------- | ------------------ |
5671| SEEK_SET | 0     | 文件起始位置处。           |
5672| SEEK_CUR    | 1     | 当前文件偏置指针位置处。 |
5673| SEEK_END    | 2     | 文件末尾位置处。 |
5674
5675## LocationType<sup>11+</sup>
5676
5677枚举,文件位置,表示该文件是否在本地或者云端存在。
5678
5679**系统能力**:SystemCapability.FileManagement.File.FileIO
5680
5681| 名称        | 值       | 说明                |
5682| ----------- | --------------- | ------------------ |
5683| LOCAl | 1     | 文件在本地存在           |
5684| CLOUD    | 2     | 文件在云端存在 |
5685
5686## AccessModeType<sup>12+</sup>
5687
5688枚举,表示需要校验的具体权限,若不填,默认校验文件是否存在。
5689
5690**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
5691
5692**系统能力**:SystemCapability.FileManagement.File.FileIO
5693
5694| 名称        | 值       | 说明                |
5695| ----------- | --------------- | ------------------ |
5696| EXIST | 0     | 文件是否存在           |
5697| WRITE    | 2     | 文件是否具有写入权限 |
5698| READ    | 4     | 文件是否具有读取权限 |
5699| READ_WRITE    | 6     | 文件是否具有读写权限 |
5700
5701## AccessFlagType<sup>12+</sup>
5702
5703枚举,表示需要校验的文件位置
5704
5705**系统能力**:SystemCapability.FileManagement.File.FileIO
5706
5707| 名称        | 值       | 说明                |
5708| ----------- | --------------- | ------------------ |
5709| LOCAL | 0     | 文件是否在本地          |
5710
5711## ReadOptions<sup>11+</sup>
5712
5713可选项类型,支持read接口使用。
5714
5715**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
5716
5717**系统能力**:SystemCapability.FileManagement.File.FileIO
5718
5719| 名称        | 类型       | 必选       | 说明                |
5720| ----------- | --------------- | ------------------ |------------------ |
5721| length | number     | 否 | 期望读取数据的长度,单位为字节。可选,默认缓冲区长度。           |
5722|  offset    | number     | 否 | 期望读取文件位置,单位为字节(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始读。 |
5723
5724## ReadTextOptions<sup>11+</sup>
5725
5726可选项类型,支持readText接口使用,ReadTextOptions继承至[ReadOptions](#readoptions11)。
5727
5728**系统能力**:SystemCapability.FileManagement.File.FileIO
5729
5730| 名称        | 类型       | 必选       | 说明                |
5731| ----------- | --------------- | ------------------ | ------------------ |
5732| length | number     | 否 | 期望读取数据的长度,单位为字节。可选,默认文件长度。           |
5733|  offset    | number     | 否 | 期望读取文件的位置,单位为字节。可选,默认从当前位置开始读取。 |
5734| encoding    | string | 否 | 当数据是 string 类型时有效,表示数据的编码方式,默认 'utf-8',仅支持 'utf-8'。   <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。    |
5735
5736## WriteOptions<sup>11+</sup>
5737
5738可选项类型,支持write接口使用,WriteOptions继承至[Options](#options11)。
5739
5740**系统能力**:SystemCapability.FileManagement.File.FileIO
5741
5742| 名称        | 类型       | 必选       | 说明                |
5743| ----------- | --------------- | ------------------ | ------------------ |
5744| length | number     | 否 | 期望写入数据的长度,单位为字节。可选,默认缓冲区长度。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。           |
5745|  offset    | number     | 否 | 期望写入文件位置,单位为字节(基于当前filePointer加上offset的位置)。可选,默认从偏置指针(filePointer)开始写。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
5746| encoding    | string | 否 | 当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。       |
5747
5748## ListFileOptions<sup>11+</sup>
5749
5750可选项类型,支持listFile接口使用。
5751
5752**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
5753
5754**系统能力**:SystemCapability.FileManagement.File.FileIO
5755
5756| 名称        | 类型       | 必选       |  说明                |
5757| ----------- | --------------- | ------------------ | ------------------ |
5758| recursion | boolean     | 否 | 是否递归子目录下文件名。可选,默认为false。当recursion为false时,返回当前目录下满足过滤要求的文件名及文件夹名。当recursion为true时,返回此目录下所有满足过滤要求的文件的相对路径(以/开头)。           |
5759|  listNum    | number     | 否 | 列出文件名数量。可选,当设置0时,列出所有文件,默认为0。 |
5760| filter    | [Filter](#filter10) | 否 | 文件过滤配置项类型。 可选,设置文件的过滤条件 |
5761
5762## ReadStream<sup>12+</sup>
5763
5764文件可读流,需要先通过[fs.createReadStream](#fscreatereadstream12)方法来构建一个ReadStream实例。ReadStream继承自数据流基类[stream](../apis-arkts/js-apis-stream.md#readable)。
5765
5766**规格**:ReadStream读到的数据为解码后的字符串,其编码格式当前仅支持'utf-8'。
5767
5768### 属性
5769
5770| 名称     | 类型   | 只读   | 可写   | 说明                                       |
5771| ------ | ------ | ---- | ---- | ---------------------------------------- |
5772| bytesRead    | number | 是    | 否    | 可读流已经读取的字节数 |
5773| path    | string | 是    | 否    | 当前可读流对应的文件路径 |
5774
5775### Seek
5776
5777seek(offset: number, whence?: WhenceType): number;
5778
5779
5780调整可读流偏置指针位置。
5781
5782**系统能力**:SystemCapability.FileManagement.File.FileIO
5783
5784**参数:**
5785
5786  | 参数名    | 类型     | 必填   | 说明                          |
5787  | ------ | ------ | ---- | --------------------------- |
5788  | offset | number | 是    | 相对偏移位置,单位为字节。 |
5789  | whence | [WhenceType](#whencetype11) | 否    | 偏移指针相对位置类型,默认值:SEEK_SET,文件起始位置处。 |
5790
5791**返回值:**
5792
5793  | 类型                   | 说明         |
5794  | --------------------- | ---------- |
5795  | number | 当前可读流偏置指针位置(相对于文件头的偏移量,单位为字节)。 |
5796
5797**错误码:**
5798
5799接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5800
5801**示例:**
5802
5803  ```ts
5804  const filePath = pathDir + "/test.txt";
5805  const rs = fs.createReadStream(filePath);
5806  const curOff = rs.seek(5, fs.WhenceType.SEEK_SET);
5807  console.info(`current offset is ${curOff}`);
5808  rs.close();
5809  ```
5810
5811### close
5812
5813close(): void
5814
5815关闭可读流。
5816
5817**系统能力**:SystemCapability.FileManagement.File.FileIO
5818
5819**错误码:**
5820
5821接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5822
5823**示例:**
5824
5825  ```ts
5826  const filePath = pathDir + "/test.txt";
5827  const rs = fs.createReadStream(filePath);
5828  rs.close();
5829  ```
5830
5831## WriteStream<sup>12+</sup>
5832
5833文件可写流,需要先通过[fs.createWriteStream](#fscreatewritestream12)方法来构建一个WriteStream实例。WriteStream继承自数据流基类[stream](../apis-arkts/js-apis-stream.md#writable)。
5834
5835### 属性
5836
5837| 名称     | 类型   | 只读   | 可写   | 说明                                       |
5838| ------ | ------ | ---- | ---- | ---------------------------------------- |
5839| bytesWritten    | number | 是    | 否    | 可写流已经写入的字节数 |
5840| path    | string | 是    | 否    | 当前可写流对应的文件路径 |
5841
5842### Seek
5843
5844seek(offset: number, whence?: WhenceType): number;
5845
5846调整可写流偏置指针位置。
5847
5848**系统能力**:SystemCapability.FileManagement.File.FileIO
5849
5850**参数:**
5851
5852  | 参数名    | 类型     | 必填   | 说明                          |
5853  | ------ | ------ | ---- | --------------------------- |
5854  | offset | number | 是    | 相对偏移位置,单位为字节。 |
5855  | whence | [WhenceType](#whencetype11) | 否    | 偏移指针相对位置类型,默认值:SEEK_SET,文件起始位置处。 |
5856
5857**返回值:**
5858
5859  | 类型                   | 说明         |
5860  | --------------------- | ---------- |
5861  | number | 当前可写流偏置指针位置(相对于文件头的偏移量,单位为字节)。 |
5862
5863**错误码:**
5864
5865接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5866
5867**示例:**
5868
5869  ```ts
5870  const filePath = pathDir + "/test.txt";
5871  const ws = fs.createWriteStream(filePath);
5872  const curOff = ws.seek(5, fs.WhenceType.SEEK_SET);
5873  console.info(`current offset is ${curOff}`);
5874  ws.close();
5875  ```
5876
5877### close
5878
5879close(): void
5880
5881关闭可写流。
5882
5883**系统能力**:SystemCapability.FileManagement.File.FileIO
5884
5885**错误码:**
5886
5887接口抛出错误码的详细介绍请参见[基础文件IO错误码](errorcode-filemanagement.md#基础文件io错误码)。
5888
5889**示例:**
5890
5891  ```ts
5892  const filePath = pathDir + "/test.txt";
5893  const ws = fs.createWriteStream(filePath);
5894  ws.close();
5895  ```
5896
5897## RandomAccessFileOptions<sup>12+</sup>
5898
5899可选项类型,支持 createRandomAccessFile 接口使用。
5900
5901**系统能力**:SystemCapability.FileManagement.File.FileIO
5902
5903| 名称        | 类型       | 必选       |  说明                |
5904| ----------- | --------------- | ------------------ | ------------------ |
5905| start   | number     | 否 | 表示期望读取文件的位置,单位为字节。可选,默认从当前位置开始读。           |
5906| end     | number     | 否 |  表示期望读取结束的位置,单位为字节。可选,默认文件末尾。 |
5907
5908## ReadStreamOptions<sup>12+</sup>
5909
5910可选项类型,支持 createReadStream 接口使用。
5911
5912**系统能力**:SystemCapability.FileManagement.File.FileIO
5913
5914| 名称        | 类型       | 必选       |  说明                |
5915| ----------- | --------------- | ------------------ | ------------------ |
5916| start   | number     | 否 | 表示期望读取文件的位置,单位为字节。可选,默认从当前位置开始读。           |
5917| end     | number     | 否 |  表示期望读取结束的位置,单位为字节。可选,默认文件末尾。 |
5918
5919## WriteStreamOptions<sup>12+</sup>
5920
5921可选项类型,支持 createWriteStream 接口使用。
5922
5923**系统能力**:SystemCapability.FileManagement.File.FileIO
5924
5925| 名称        | 类型       | 必选       |  说明                |
5926| ----------- | --------------- | ------------------ | ------------------ |
5927| start   | number     | 否 | 表示期望写入文件的位置,单位为字节。可选,默认文件起始位置。           |
5928| 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的方式打开文件。 |
5929