• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.file.fileAccess (User File Access and Management)
2
3The **fileAccess** module provides a framework for accessing and operating user files based on the ExtensionAbility mechanism. This module interacts with file management services, such as the media library and external storage management service, and provides a set of unified interfaces for system applications to access and manage files. The media library service allows access to user files on local and distributed devices. The external storage management service allows access to the user files stored on devices, such as shared disks, USB flash drives, and SD cards.
4
5>**NOTE**
6>
7> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8> - The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by **FilePicker** and **FileManager**.
9
10## Modules to Import
11
12```ts
13import fileAccess from '@ohos.file.fileAccess';
14```
15
16## fileAccess.getFileAccessAbilityInfo
17
18getFileAccessAbilityInfo() : Promise<Array<Want>>
19
20Obtains information about all Wants with **extension** set to **fileAccess** in the system. A Want contains information for starting an ability. This API uses a promise to return the result.
21
22**Model restriction**: This API can be used only in the stage model.
23
24**System capability**: SystemCapability.FileManagement.UserFileService
25
26**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
27
28**Return value**
29
30  | Type| Description|
31  | --- | -- |
32  | Promise<Array<[Want](js-apis-app-ability-want.md)>> | Promise used to return the Want information obtained.|
33
34**Error codes**
35
36For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
37
38**Example**
39
40  ```ts
41  import { BusinessError } from '@ohos.base';
42  import Want from '@ohos.app.ability.Want';
43  async getFileAccessAbilityInfo() {
44    let wantInfos: Array<Want> = [];
45    try {
46      wantInfos = await fileAccess.getFileAccessAbilityInfo();
47      console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos));
48    } catch (err) {
49      let error: BusinessError = err as BusinessError;
50      console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message);
51    }
52  }
53  ```
54
55## fileAccess.getFileAccessAbilityInfo
56
57getFileAccessAbilityInfo(callback: AsyncCallback&lt;Array&lt;Want&gt;&gt;): void
58
59Obtains information about all Wants with **extension** set to **fileAccess** in the system. A Want contains information for starting an ability. This API uses an asynchronous callback to return the result.
60
61**Model restriction**: This API can be used only in the stage model.
62
63**System capability**: SystemCapability.FileManagement.UserFileService
64
65**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
66
67**Parameters**
68
69  | Name| Type| Mandatory| Description|
70  | --- | --- | --- | -- |
71  | callback | AsyncCallback&lt;Array&lt;[Want](js-apis-app-ability-want.md)&gt;&gt; | Yes| Promise used to return the Want information obtained.|
72
73**Error codes**
74
75For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
76
77**Example**
78
79  ```ts
80  import { BusinessError } from '@ohos.base';
81  import Want from '@ohos.app.ability.Want';
82  async getFileAccessAbilityInfo() {
83    try {
84      fileAccess.getFileAccessAbilityInfo((err: BusinessError, wantInfos: Array<Want>) => {
85        if (err) {
86          console.error("Failed to getFileAccessAbilityInfo in async, errCode:" + err.code + ", errMessage:" + err.message);
87          return;
88        }
89        console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos));
90      });
91    } catch (err) {
92      let error: BusinessError = err as BusinessError;
93      console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message);
94    }
95  }
96  ```
97
98## fileAccess.createFileAccessHelper
99
100createFileAccessHelper(context: Context, wants: Array&lt;Want&gt;) : FileAccessHelper
101
102Synchronously creates a **Helper** object to connect to the specified Wants. The **Helper** object provides file access and management capabilities.
103
104**Model restriction**: This API can be used only in the stage model.
105
106**System capability**: SystemCapability.FileManagement.UserFileService
107
108**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
109
110**Parameters**
111
112  | Name| Type| Mandatory| Description|
113  | --- | --- | --- | -- |
114  | context | [Context](js-apis-inner-application-context.md) | Yes| Context of the ability.|
115  | wants | Array&lt;[Want](js-apis-app-ability-want.md)&gt; | Yes| Wants to connect.|
116
117**Return value**
118
119  | Type| Description|
120  | --- | -- |
121  | [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|
122
123**Error codes**
124
125For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
126
127**Example**
128
129  ```ts
130  import { BusinessError } from '@ohos.base';
131  import Want from '@ohos.app.ability.Want';
132  import common from '@ohos.app.ability.common';
133  let context = getContext(this) as common.UIAbilityContext;
134  function createFileAccessHelper01() {
135    let fileAccessHelper: fileAccess.FileAccessHelper;
136    // Obtain wantInfos by using getFileAccessAbilityInfo().
137    let wantInfos: Array<Want> = [
138      {
139        bundleName: "com.ohos.UserFile.ExternalFileManager",
140        abilityName: "FileExtensionAbility",
141      },
142    ]
143    try {
144      // context is passed by EntryAbility.
145      fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos);
146      if (!fileAccessHelper) {
147        console.error("createFileAccessHelper interface returns an undefined object");
148      }
149    } catch (err) {
150      let error: BusinessError = err as BusinessError;
151      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
152    }
153  }
154  ```
155
156## fileAccess.createFileAccessHelper
157
158createFileAccessHelper(context: Context) : FileAccessHelper
159
160Synchronously creates a **Helper** object to connect to all file management services in the system.
161
162**Model restriction**: This API can be used only in the stage model.
163
164**System capability**: SystemCapability.FileManagement.UserFileService
165
166**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
167
168**Parameters**
169
170  | Name| Type| Mandatory| Description|
171  | --- | --- | --- | -- |
172  | context | [Context](js-apis-inner-application-context.md) | Yes| Context of the ability.|
173
174**Return value**
175
176  | Type| Description|
177  | --- | -- |
178  | [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|
179
180**Error codes**
181
182For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
183
184**Example**
185
186  ```ts
187  import { BusinessError } from '@ohos.base';
188  import common from '@ohos.app.ability.common';
189  let context = getContext(this) as common.UIAbilityContext;
190  function createFileAccessHelper02() {
191    let fileAccessHelperAllServer: fileAccess.FileAccessHelper;
192    // Create a Helper object to interact with all file management services configured with fileAccess in the system.
193    try {
194      // context is passed by EntryAbility.
195      fileAccessHelperAllServer = fileAccess.createFileAccessHelper(context);
196      if (!fileAccessHelperAllServer)
197        console.error("createFileAccessHelper interface returns an undefined object");
198    } catch (err) {
199      let error: BusinessError = err as BusinessError;
200      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
201    }
202  }
203  ```
204
205## FileInfo
206
207Provides the file or directory attribute information and APIs.
208
209**Model restriction**: This API can be used only in the stage model.
210
211**System capability**: SystemCapability.FileManagement.UserFileService
212
213**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
214
215### Attributes
216
217| Name| Type  | Readable| Writable| Description    |
218| ------ | ------ | -------- | ------ | -------- |
219| uri | string | Yes| No| URI of the file or directory.|
220| relativePath<sup>10+</sup> | string | Yes| No| Relative path of the file or directory.|
221| fileName | string | Yes| No| Name of the file or directory.|
222| mode | number | Yes| No| Permissions on the file or directory.|
223| size | number | Yes| No|  Size of the file or directory.|
224| mtime | number | Yes| No|  Time when the file or directory was last modified.|
225| mimeType | string | Yes| No|  Multipurpose Internet Mail Extensions (MIME) type of the file or directory.|
226
227### listFile
228
229listFile(filter?: Filter) : FileIterator
230
231Synchronously obtains a **FileIterator** object that lists the next-level files (directories) matching the conditions of the filter from a directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, only built-in storage devices support the file filter.
232
233**Model restriction**: This API can be used only in the stage model.
234
235**System capability**: SystemCapability.FileManagement.UserFileService
236
237**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
238
239**Parameters**
240
241  | Name| Type| Mandatory| Description|
242  | --- | --- | -- | -- |
243  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
244
245**Return value**
246
247  | Type| Description|
248  | --- | -- |
249  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|
250
251**Error codes**
252
253For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
254
255**Example**
256
257  ```ts
258  import { BusinessError } from '@ohos.base';
259  // fileInfoDir indicates information about a directory.
260  // let filter = { suffix : [".txt", ".jpg", ".xlsx"] };
261  let fileInfoDir: fileAccess.FileInfo; // = fileInfos[0];
262  let subfileInfos: Array<fileAccess.FileInfo> = [];
263  let isDone: boolean = false;
264  try {
265    let fileIterator = fileInfoDir.listFile();
266    // listFile() with the filter implementation.
267    // let fileIterator = fileInfoDir.listFile(filter);
268    if (!fileIterator) {
269      console.error("listFile interface returns an undefined object");
270    }
271    while (!isDone) {
272      let result = fileIterator.next();
273      console.log("next result = " + JSON.stringify(result));
274      isDone = result.done;
275      if (!isDone) {
276        subfileInfos.push(result.value);
277      }
278    }
279  } catch (err) {
280    let error: BusinessError = err as BusinessError;
281    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
282  }
283  ```
284
285### scanFile
286
287scanFile(filter?: Filter) : FileIterator;
288
289Synchronously obtains a **FileIterator** object that recursively retrieves the files matching the conditions of the filter from a directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, this API supports only built-in storage devices.
290
291**Model restriction**: This API can be used only in the stage model.
292
293**System capability**: SystemCapability.FileManagement.UserFileService
294
295**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
296
297**Parameters**
298
299  | Name| Type| Mandatory| Description|
300  | --- | --- | -- | -- |
301  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
302
303**Return value**
304
305  | Type| Description|
306  | --- | -- |
307  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|
308
309**Error codes**
310
311For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
312
313**Example**
314
315  ```ts
316  import { BusinessError } from '@ohos.base';
317  // fileInfoDir indicates information about a directory.
318  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
319  let fileInfoDir: fileAccess.FileInfo; // = fileInfos[0];
320  let subfileInfos: Array<fileAccess.FileInfo> = [];
321  let isDone: boolean = false;
322  try {
323    let fileIterator = fileInfoDir.scanFile();
324    // scanFile() with the filter implementation.
325    // let fileIterator = fileInfoDir.scanFile(filter);
326    if (!fileIterator) {
327      console.error("scanFile interface returns an undefined object");
328    }
329    while (!isDone) {
330      let result = fileIterator.next();
331      console.log("next result = " + JSON.stringify(result));
332      isDone = result.done;
333      if (!isDone) {
334        subfileInfos.push(result.value);
335      }
336    }
337  } catch (err) {
338    let error: BusinessError = err as BusinessError;
339    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
340  }
341  ```
342
343## FileIterator
344
345Provides the **FileIterator** object.
346
347**Model restriction**: This API can be used only in the stage model.
348
349**System capability**: SystemCapability.FileManagement.UserFileService
350
351**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
352
353### next
354
355next() : { value: FileInfo, done: boolean }
356
357Obtains information about the next-level files or directories.
358
359**Model restriction**: This API can be used only in the stage model.
360
361**System capability**: SystemCapability.FileManagement.UserFileService
362
363**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
364
365**Return value**
366
367| Type| Description|
368| --- | -- |
369| {value: [FileInfo](#fileinfo), done: boolean} | File or directory information obtained. This method traverses the specified directory until **true** is returned. The **value** field contains the file or directory information obtained.|
370
371**Error codes**
372
373For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
374
375## RootInfo
376
377Provides the device's root attribute information and APIs.
378
379**Model restriction**: This API can be used only in the stage model.
380
381**System capability**: SystemCapability.FileManagement.UserFileService
382
383**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
384
385### Attributes
386
387| Name| Type  | Readable| Writable| Description    |
388| ------ | ------ | -------- | ------ | -------- |
389| deviceType | number | Yes| No|Type of the device.|
390| uri | string | Yes| No| Root directory URI of the device.|
391| relativePath<sup>10+</sup> | string | Yes| No| Relative path of the root directory.|
392| displayName | string | Yes| No| Device name.|
393| deviceFlags | number | Yes| No| Capabilities supported by the device.|
394
395### listFile
396
397listFile(filter?: Filter) : FileIterator
398
399Synchronously obtains a **FileIterator** object that lists the first-level files (directories) matching the conditions of the filter from the device root directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, only built-in storage devices support the file filter.
400
401**Model restriction**: This API can be used only in the stage model.
402
403**System capability**: SystemCapability.FileManagement.UserFileService
404
405**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
406
407**Parameters**
408
409  | Name| Type| Mandatory| Description|
410  | --- | --- | -- | -- |
411  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
412
413**Return value**
414
415  | Type| Description|
416  | --- | -- |
417  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|
418
419**Error codes**
420
421For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
422
423**Example**
424
425  ```ts
426  import { BusinessError } from '@ohos.base';
427  // Obtain rootInfos by using getRoots().
428  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
429  let rootInfo: fileAccess.RootInfo; // = rootinfos[0];
430  let fileInfos: Array<fileAccess.FileInfo> = [];
431  let isDone: boolean = false;
432  try {
433    let fileIterator = rootInfo.listFile();
434    // listFile() with the filter implementation.
435    // let fileIterator = rootInfo.listFile(filter);
436    if (!fileIterator) {
437      console.error("listFile interface returns an undefined object");
438    }
439    while (!isDone) {
440      let result = fileIterator.next();
441      console.log("next result = " + JSON.stringify(result));
442      isDone = result.done;
443      if (!isDone) {
444        fileInfos.push(result.value);
445      }
446    }
447  } catch (err) {
448    let error: BusinessError = err as BusinessError;
449    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
450  }
451  ```
452
453### scanFile
454
455scanFile(filter?: Filter) : FileIterator
456
457Synchronously obtains a **FileIterator** object that recursively retrieves the files matching the conditions of the filter from the device root directory and returns [FileInfo](#fileinfo)using [next()](#next). Currently, this API supports only built-in storage devices.
458
459**Model restriction**: This API can be used only in the stage model.
460
461**System capability**: SystemCapability.FileManagement.UserFileService
462
463**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
464
465**Parameters**
466
467  | Name| Type| Mandatory| Description|
468  | --- | --- | -- | -- |
469  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
470
471**Return value**
472
473  | Type| Description|
474  | --- | -- |
475  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|
476
477**Error codes**
478
479For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
480
481**Example**
482
483  ```ts
484  import { BusinessError } from '@ohos.base';
485  // Obtain rootInfos by using getRoots().
486  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
487  let rootInfo: fileAccess.RootInfo; // = rootinfos[0];
488  let fileInfos: Array<fileAccess.FileInfo> = [];
489  let isDone: boolean = false;
490  try {
491    let fileIterator = rootInfo.scanFile();
492    // scanFile with the filter implementation.
493    // let fileIterator = rootInfo.scanFile(filter);
494    if (!fileIterator) {
495      console.error("scanFile interface returns undefined object");
496    }
497    while (!isDone) {
498      let result = fileIterator.next();
499      console.log("next result = " + JSON.stringify(result));
500      isDone = result.done;
501      if (!isDone) {
502        fileInfos.push(result.value);
503      }
504    }
505  } catch (err) {
506    let error: BusinessError = err as BusinessError;
507    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
508  }
509  ```
510
511## RootIterator
512
513Provides an iterator object of the device root directory.
514
515**Model restriction**: This API can be used only in the stage model.
516
517**System capability**: SystemCapability.FileManagement.UserFileService
518
519**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
520
521### next
522
523next() : { value: RootInfo, done: boolean }
524
525Obtains the root directory of the next-level device.
526
527**Model restriction**: This API can be used only in the stage model.
528
529**System capability**: SystemCapability.FileManagement.UserFileService
530
531**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
532
533**Return value**
534
535| Type| Description|
536| --- | -- |
537| {value: [RootInfo](#rootinfo), done: boolean} | Root directory information obtained. This method traverses the directory until **true** is returned. The **value** field contains the root directory information.|
538
539**Error codes**
540
541For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
542
543## FileAccessHelper
544
545Provides a **FileAccessHelper** object.
546
547**System capability**: SystemCapability.FileManagement.UserFileService
548
549**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
550
551### getRoots
552
553getRoots() : Promise&lt;RootIterator&gt;
554
555Obtains information about the device root nodes of the file management service connected to the **Helper** object. This API uses a promise to return a **RootIterator** object,
556which returns [RootInfo](#rootinfo) by using [next](#next-1).
557
558**System capability**: SystemCapability.FileManagement.UserFileService
559
560**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
561
562**Return value**
563
564| Type| Description|
565| --- | -- |
566| Promise&lt;[RootIterator](#rootiterator)&gt; | Promise used to return the **RootIterator** object obtained.|
567
568**Error codes**
569
570For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
571
572**Example**
573
574  ```ts
575  import { BusinessError } from '@ohos.base';
576  async function getRoots() {
577    let rootIterator: fileAccess.RootIterator;
578    let rootinfos: Array<fileAccess.RootInfo> = [];
579    let isDone: boolean = false;
580    try {
581      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
582      rootIterator = await fileAccessHelper.getRoots();
583      if (!rootIterator) {
584        console.error("getRoots interface returns an undefined object");
585      }
586      while (!isDone) {
587        let result = rootIterator.next();
588        console.log("next result = " + JSON.stringify(result));
589        isDone = result.done;
590        if (!isDone) {
591          rootinfos.push(result.value);
592        }
593      }
594    } catch (err) {
595      let error: BusinessError = err as BusinessError;
596      console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
597    }
598  }
599  ```
600
601### getRoots
602
603getRoots(callback:AsyncCallback&lt;RootIterator&gt;) : void
604
605Obtains information about the device root nodes of the file management service connected to the **Helper** object. This API uses an asynchronous callback to return a **RootIterator** object,
606which returns [RootInfo](#rootinfo) by using [next](#next-1).
607
608**System capability**: SystemCapability.FileManagement.UserFileService
609
610**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
611
612**Parameters**
613
614| Name| Type| Mandatory| Description|
615| --- | --- | --- | -- |
616| callback | AsyncCallback&lt;[RootIterator](#rootiterator)&gt; | Yes| Callback invoked to return the **RootIterator** object obtained.|
617
618**Error codes**
619
620For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
621
622**Example**
623
624  ```ts
625  import { BusinessError } from '@ohos.base';
626  async function getRoots() {
627    let rootinfos: Array<fileAccess.RootInfo> = [];
628    let isDone: boolean = false;
629    try {
630      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
631      fileAccessHelper.getRoots((err: BusinessError, rootIterator: fileAccess.RootIterator) => {
632        if (err) {
633          console.error("Failed to getRoots in async, errCode:" + err.code + ", errMessage:" + err.message);
634        }
635        while (!isDone) {
636          let result = rootIterator.next();
637          console.log("next result = " + JSON.stringify(result));
638          isDone = result.done;
639          if (!isDone) {
640            rootinfos.push(result.value);
641          }
642        }
643      });
644    } catch (err) {
645      let error: BusinessError = err as BusinessError;
646      console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
647    }
648  }
649  ```
650
651### createFile
652
653createFile(uri: string, displayName: string) : Promise&lt;string&gt;
654
655Creates a file in a directory. This API uses a promise to return the result.
656
657**System capability**: SystemCapability.FileManagement.UserFileService
658
659**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
660
661**Parameters**
662
663| Name| Type| Mandatory| Description|
664| --- | --- | --- | -- |
665| uri | string | Yes| URI of the destination directory for the file to create.|
666| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
667
668**Return value**
669
670| Type| Description|
671| --- | -- |
672| Promise&lt;string&gt; | Promise used to return the URI of the file created.|
673
674**Error codes**
675
676For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
677
678**Example**
679
680  ```ts
681  import { BusinessError } from '@ohos.base';
682  // A built-in storage directory is used as an example.
683  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
684  // You can use the URI obtained.
685  let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
686  let displayName: string = "file1";
687  let fileUri: string;
688  try {
689    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
690    fileUri = await fileAccessHelper.createFile(sourceUri, displayName);
691    if (!fileUri) {
692      console.error("createFile return undefined object");
693    }
694    console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri));
695  } catch (err) {
696    let error: BusinessError = err as BusinessError;
697    console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
698  }
699  ```
700
701### createFile
702
703createFile(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
704
705Creates a file in a directory. This API uses an asynchronous callback to return the result.
706
707**System capability**: SystemCapability.FileManagement.UserFileService
708
709**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
710
711**Parameters**
712
713| Name| Type| Mandatory| Description|
714| --- | --- | --- | -- |
715| uri | string | Yes| URI of the destination directory for the file to create.|
716| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
717| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the file created.|
718
719**Error codes**
720
721For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
722
723**Example**
724
725  ```ts
726  import { BusinessError } from '@ohos.base';
727  // A built-in storage directory is used as an example.
728  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
729  // You can use the URI obtained.
730  let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
731  let displayName: string = "file1";
732  try {
733    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
734    fileAccessHelper.createFile(sourceUri, displayName, (err: BusinessError, fileUri: string) => {
735      if (err) {
736        console.error("Failed to createFile in async, errCode:" + err.code + ", errMessage:" + err.message);
737        return;
738      }
739      console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri));
740    });
741  } catch (err) {
742    let error: BusinessError = err as BusinessError;
743    console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
744  }
745  ```
746
747### mkDir
748
749mkDir(parentUri: string, displayName: string) : Promise&lt;string&gt;
750
751Creates a directory. This API uses a promise to return the result.
752
753**System capability**: SystemCapability.FileManagement.UserFileService
754
755**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
756
757**Parameters**
758
759| Name| Type| Mandatory| Description|
760| --- | --- | --- | -- |
761| parentUri | string | Yes| URI of the destination directory for the directory to create.|
762| displayName | string | Yes| Name of the directory to create.|
763
764**Return value**
765
766| Type| Description|
767| --- | -- |
768| Promise&lt;string&gt; | Promise used to return the URI of the directory created.|
769
770**Error codes**
771
772For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
773
774**Example**
775
776  ```ts
777  import { BusinessError } from '@ohos.base';
778  // A built-in storage directory is used as an example.
779  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
780  // You can use the URI obtained.
781  let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
782  let dirName: string = "dirTest";
783  let dirUri: string;
784  try {
785    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
786    dirUri = await fileAccessHelper.mkDir(sourceUri, dirName);
787    if (!dirUri) {
788      console.error("mkDir return undefined object");
789    }
790    console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri));
791  } catch (err) {
792    let error: BusinessError = err as BusinessError;
793    console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message);
794  }
795  ```
796
797### mkDir
798
799mkDir(parentUri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
800
801Creates a directory. This API uses an asynchronous callback to return the result.
802
803**System capability**: SystemCapability.FileManagement.UserFileService
804
805**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
806
807**Parameters**
808
809| Name| Type| Mandatory| Description|
810| --- | --- | --- | -- |
811| parentUri | string | Yes| URI of the destination directory for the directory to create.|
812| displayName | string | Yes| Name of the directory to create.|
813| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the directory created.|
814
815**Error codes**
816
817For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
818
819**Example**
820
821  ```ts
822  import { BusinessError } from '@ohos.base';
823  // A built-in storage directory is used as an example.
824  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
825  // You can use the URI obtained.
826  let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
827  let dirName: string = "dirTest";
828  try {
829    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
830    fileAccessHelper.mkDir(sourceUri, dirName, (err: BusinessError, dirUri: string) => {
831      if (err) {
832        console.error("Failed to mkDir in async, errCode:" + err.code + ", errMessage:" + err.message);
833        return;
834      }
835      console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri));
836    });
837  } catch (err) {
838    let error: BusinessError = err as BusinessError;
839    console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message);
840  }
841  ```
842
843### openFile
844
845openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;
846
847Opens a file. This API uses a promise to return the result.
848
849**System capability**: SystemCapability.FileManagement.UserFileService
850
851**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
852
853**Parameters**
854
855| Name| Type| Mandatory| Description|
856| --- | --- | --- | -- |
857| uri | string | Yes| URI of the file to open.|
858| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
859
860**Return value**
861
862| Type| Description|
863| --- | -- |
864| Promise&lt;number&gt; | Promise used to return the file descriptor (FD) of the file opened.|
865
866**Error codes**
867
868For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
869
870**Example**
871
872  ```ts
873  import { BusinessError } from '@ohos.base';
874  async function openFile01() {
875    // A built-in storage directory is used as an example.
876    // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
877    // You can use the URI obtained.
878    let targetUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
879    try {
880      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
881      let fd = await fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ);
882    } catch (err) {
883      let error: BusinessError = err as BusinessError;
884      console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message);
885    }
886  }
887  ```
888
889### openFile
890
891openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : void
892
893Opens a file. This API uses an asynchronous callback to return the result.
894
895**System capability**: SystemCapability.FileManagement.UserFileService
896
897**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
898
899**Parameters**
900
901| Name| Type| Mandatory| Description|
902| --- | --- | --- | -- |
903| uri | string | Yes| URI of the file to open.|
904| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
905| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the FD of the file opened.|
906
907**Error codes**
908
909For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
910
911**Example**
912
913  ```ts
914  import { BusinessError } from '@ohos.base';
915  // A built-in storage directory is used as an example.
916  // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
917  // You can use the URI obtained.
918  let targetUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
919  try {
920    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
921    fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ, (err: BusinessError, fd: number) => {
922      if (err) {
923        console.error("Failed to openFile in async, errCode:" + err.code + ", errMessage:" + err.message);
924      }
925      console.log("openFile sucess, fd: " + fd);
926    });
927  } catch (err) {
928    let error: BusinessError = err as BusinessError;
929    console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message);
930  }
931  ```
932
933### delete
934
935delete(uri: string) : Promise&lt;number&gt;
936
937Deletes a file or directory. This API uses a promise to return the result.
938
939**System capability**: SystemCapability.FileManagement.UserFileService
940
941**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
942
943**Parameters**
944
945| Name| Type| Mandatory| Description|
946| --- | --- | --- | -- |
947| uri | string | Yes| URI of the file or directory to delete.|
948
949**Return value**
950
951| Type| Description|
952| --- | -- |
953| Promise&lt;number&gt | Promise used to return the result.|
954
955**Error codes**
956
957For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
958
959**Example**
960
961  ```ts
962  import { BusinessError } from '@ohos.base';
963  async function deleteFile01() {
964    // A built-in storage directory is used as an example.
965    // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
966    // You can use the URI obtained.
967    let targetUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
968    try {
969      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
970      let code = await fileAccessHelper.delete(targetUri);
971      if (code != 0)
972        console.error("delete failed, code " + code);
973    } catch (err) {
974      let error: BusinessError = err as BusinessError;
975      console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message);
976    }
977  }
978  ```
979
980### delete
981
982delete(uri: string, callback: AsyncCallback&lt;number&gt;) : void
983
984Deletes a file or directory. This API uses an asynchronous callback to return the result.
985
986**System capability**: SystemCapability.FileManagement.UserFileService
987
988**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
989
990**Parameters**
991
992| Name| Type| Mandatory| Description|
993| --- | --- | --- | -- |
994| uri | string | Yes| URI of the file or directory to delete.|
995| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result.|
996
997**Error codes**
998
999For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1000
1001**Example**
1002
1003  ```ts
1004  import { BusinessError } from '@ohos.base';
1005  // A built-in storage directory is used as an example.
1006  // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
1007  // You can use the URI obtained.
1008  let targetUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1009  try {
1010    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1011    fileAccessHelper.delete(targetUri, (err: BusinessError, code: number) => {
1012      if (err) {
1013        console.error("Failed to delete in async, errCode:" + err.code + ", errMessage:" + err.message);
1014        return;
1015      }
1016      console.log("delete sucess, code: " + code);
1017    });
1018  } catch (err) {
1019    let error: BusinessError = err as BusinessError;
1020    console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message);
1021  }
1022  ```
1023
1024### move
1025
1026move(sourceFile: string, destFile: string) : Promise&lt;string&gt;
1027
1028Moves a file or directory. This API uses a promise to return the result. Currently, this API does not support move of files or directories across devices.
1029
1030**System capability**: SystemCapability.FileManagement.UserFileService
1031
1032**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1033
1034**Parameters**
1035
1036| Name| Type| Mandatory| Description|
1037| --- | --- | --- | -- |
1038| sourceFile | string | Yes| URI of the file or directory to move.|
1039| destFile | string | Yes| URI of the destination directory, to which the file or directory will be moved.|
1040
1041**Return value**
1042
1043| Type| Description|
1044| ----- | ------ |
1045| Promise&lt;string&gt; | Promise used to return the URI of the file or directory in the destination directory.|
1046
1047**Error codes**
1048
1049For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1050
1051**Example**
1052
1053  ```ts
1054  import { BusinessError } from '@ohos.base';
1055  async function moveFile01() {
1056    // A built-in storage directory is used as an example.
1057    // In the sample code, sourceFile and destFile indicate the files and directories in the Download directory. The URI is the URI in fileInfo.
1058    // You can use the URI obtained.
1059    let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1060    let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1061    try {
1062      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1063      let fileUri = await fileAccessHelper.move(sourceFile, destFile);
1064      console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
1065    } catch (err) {
1066      let error: BusinessError = err as BusinessError;
1067      console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
1068    }
1069  }
1070  ```
1071
1072### move
1073
1074move(sourceFile: string, destFile: string, callback: AsyncCallback&lt;string&gt;) : void
1075
1076Moves a file or directory. This API uses an asynchronous callback to return the result. Currently, this API does not support move of files or directories across devices.
1077
1078**System capability**: SystemCapability.FileManagement.UserFileService
1079
1080**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1081
1082**Parameters**
1083
1084| Name| Type| Mandatory| Description|
1085| --- | --- | --- | -- |
1086| sourceFile | string | Yes| URI of the file or directory to move.|
1087| destFile | string | Yes| URI of the destination directory, to which the file or directory will be moved.|
1088| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the file or directory in the destination directory.|
1089
1090**Error codes**
1091
1092For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1093
1094**Example**
1095
1096  ```ts
1097  import { BusinessError } from '@ohos.base';
1098  // A built-in storage directory is used as an example.
1099  // In the sample code, sourceFile and destFile indicate the files and directories in the Download directory. The URI is the URI in fileInfo.
1100  // You can use the URI obtained.
1101  let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1102  let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1103  try {
1104    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1105    fileAccessHelper.move(sourceFile, destFile, (err: BusinessError, fileUri: string) => {
1106      if (err) {
1107        console.error("Failed to move in async, errCode:" + err.code + ", errMessage:" + err.message);
1108        return;
1109      }
1110      console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
1111    });
1112  } catch (err) {
1113    let error: BusinessError = err as BusinessError;
1114    console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
1115  }
1116  ```
1117
1118### rename
1119
1120rename(uri: string, displayName: string) : Promise&lt;string&gt;
1121
1122Renames a file or directory. This API uses a promise to return the result.
1123
1124**System capability**: SystemCapability.FileManagement.UserFileService
1125
1126**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1127
1128**Parameters**
1129
1130| Name| Type| Mandatory| Description|
1131| --- | --- | --- | -- |
1132| uri | string | Yes| URI of the file or directory to rename.|
1133| displayName | string | Yes| New name of the file or directory, which can contain the file name extension.|
1134
1135**Return value**
1136
1137| Type| Description|
1138| --- | -- |
1139| Promise&lt;string&gt; | Promise used to return the URI of the renamed file or directory.|
1140
1141**Error codes**
1142
1143For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1144
1145**Example**
1146
1147  ```ts
1148  import { BusinessError } from '@ohos.base';
1149  async function renameFile01() {
1150    // A built-in storage directory is used as an example.
1151    // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
1152    // You can use the URI obtained.
1153    let sourceDir: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1154    try {
1155      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1156      let DestDir = await fileAccessHelper.rename(sourceDir, "testDir");
1157      console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
1158    } catch (err) {
1159      let error: BusinessError = err as BusinessError;
1160      console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message);
1161    }
1162  }
1163  ```
1164
1165### rename
1166
1167rename(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
1168
1169Renames a file or directory. This API uses an asynchronous callback to return the result.
1170
1171**System capability**: SystemCapability.FileManagement.UserFileService
1172
1173**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1174
1175**Parameters**
1176
1177| Name| Type| Mandatory| Description|
1178| --- | --- | --- | -- |
1179| uri | string | Yes| URI of the file or directory to rename.|
1180| displayName | string | Yes| New name of the file or directory, which can contain the file name extension.|
1181| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the renamed file or directory.|
1182
1183**Error codes**
1184
1185For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1186
1187**Example**
1188
1189  ```ts
1190  import { BusinessError } from '@ohos.base';
1191  // A built-in storage directory is used as an example.
1192  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
1193  // You can use the URI obtained.
1194  let sourceDir: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1195  try {
1196    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1197    fileAccessHelper.rename(sourceDir, "testDir", (err: BusinessError, DestDir: string) => {
1198      if (err) {
1199        console.error("Failed to rename in async, errCode:" + err.code + ", errMessage:" + err.message);
1200      }
1201      console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
1202    });
1203  } catch (err) {
1204    let error: BusinessError = err as BusinessError;
1205    console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message);
1206  }
1207  ```
1208
1209### access
1210
1211access(sourceFileUri: string) : Promise&lt;boolean&gt;
1212
1213Checks whether a file or directory exists. This API uses a promise to return the result.
1214
1215**System capability**: SystemCapability.FileManagement.UserFileService
1216
1217**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1218
1219**Parameters**
1220
1221| Name| Type| Mandatory| Description|
1222| --- | --- | --- | -- |
1223| sourceFileUri | string | Yes| URI of the file or directory to check.|
1224
1225**Return value**
1226
1227| Type| Description|
1228| --- | -- |
1229| Promise&lt;boolean&gt; | Promise used to return the result.|
1230
1231**Error codes**
1232
1233For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1234
1235**Example**
1236
1237  ```ts
1238  import { BusinessError } from '@ohos.base';
1239  // A built-in storage directory is used as an example.
1240  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
1241  // You can use the URI obtained.
1242  async function accessFunc() {
1243    let sourceDir: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1244    try {
1245      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1246      let existJudgment = await fileAccessHelper.access(sourceDir);
1247      if (existJudgment) {
1248        console.log("sourceDir exists");
1249      } else {
1250        console.log("sourceDir does not exist");
1251      }
1252    } catch (err) {
1253      let error: BusinessError = err as BusinessError;
1254      console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message);
1255    }
1256  }
1257  ```
1258
1259### access
1260
1261access(sourceFileUri: string, callback: AsyncCallback&lt;boolean&gt;) : void
1262
1263Checks whether a file or directory exists. This API uses an asynchronous callback to return the result.
1264
1265**System capability**: SystemCapability.FileManagement.UserFileService
1266
1267**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1268
1269**Parameters**
1270
1271| Name| Type| Mandatory| Description|
1272| --- | --- | --- | -- |
1273| sourceFileUri | string | Yes| URI of the file or directory to check.|
1274| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback invoked to return the result.|
1275
1276**Error codes**
1277
1278For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1279
1280**Example**
1281
1282  ```ts
1283  import { BusinessError } from '@ohos.base';
1284  // A built-in storage directory is used as an example.
1285  // In the sample code, sourceDir indicates a folder in the Download directory. The URI is the URI in fileInfo.
1286  // You can use the URI obtained.
1287  let sourceDir: string = "file://docs/storage/Users/currentUser/Download/test";
1288  try {
1289    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1290    fileAccessHelper.access(sourceDir, (err: BusinessError, existJudgment: boolean) => {
1291      if (err) {
1292        console.error("Failed to access in async, errCode:" + err.code + ", errMessage:" + err.message);
1293        return;
1294      }
1295      if (existJudgment)
1296        console.log("sourceDir exists");
1297      else
1298        console.log("sourceDir does not exist");
1299    });
1300  } catch (err) {
1301    let error: BusinessError = err as BusinessError;
1302    console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message);
1303  }
1304  ```
1305
1306### getFileInfoFromUri<sup>10+</sup>
1307
1308getFileInfoFromUri(uri: string) : Promise\<FileInfo>
1309
1310Obtains a **FileInfo** object based on the specified URI. This API uses a promise to return the result.
1311
1312**System capability**: SystemCapability.FileManagement.UserFileService
1313
1314**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1315
1316**Parameters**
1317
1318| Name| Type| Mandatory| Description|
1319| --- | --- | --- | -- |
1320| uri | string | Yes| URI of the file or directory.|
1321
1322**Return value**
1323
1324| Type| Description|
1325| --- | -- |
1326| Promise\<[FileInfo](#fileinfo)> | Promise used to return the **FileInfo** object obtained.|
1327
1328**Example**
1329
1330  ```ts
1331  import { BusinessError } from '@ohos.base';
1332  // A built-in storage directory is used as an example.
1333  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
1334  // You can use the URI obtained.
1335  async function getUri() {
1336    let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
1337    try {
1338      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1339      let fileInfo = await fileAccessHelper.getFileInfoFromUri(sourceUri);
1340    } catch (err) {
1341      let error: BusinessError = err as BusinessError;
1342      console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message);
1343    }
1344  }
1345  ```
1346
1347### getFileInfoFromUri<sup>10+</sup>
1348
1349getFileInfoFromUri(uri: string, callback: AsyncCallback\<FileInfo>) : void
1350
1351Obtains a **FileInfo** object based on the specified URI. This API uses an asynchronous callback to return the result.
1352
1353**System capability**: SystemCapability.FileManagement.UserFileService
1354
1355**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1356
1357**Parameters**
1358
1359  | Name| Type| Mandatory| Description|
1360  | --- | --- | --- | -- |
1361  | uri | string | Yes| URI of the file or directory.|
1362  | callback | AsyncCallback&lt;[FileInfo](#fileinfo)&gt; | Yes| Callback invoked to return the **FileInfo** object obtained.|
1363
1364**Example**
1365
1366  ```ts
1367  import { BusinessError } from '@ohos.base';
1368  // A built-in storage directory is used as an example.
1369  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
1370  // You can use the URI obtained.
1371  let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
1372  try {
1373    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1374    fileAccessHelper.getFileInfoFromUri(sourceUri, (err: BusinessError, fileInfo: fileAccess.FileInfo) => {
1375      if (err) {
1376        console.error("Failed to getFileInfoFromUri in async, errCode:" + err.code + ", errMessage:" + err.message);
1377        return;
1378      }
1379      console.log("getFileInfoFromUri success, fileInfo: " + JSON.stringify(fileInfo));
1380    });
1381  } catch (err) {
1382    let error: BusinessError = err as BusinessError;
1383    console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message);
1384  }
1385  ```
1386
1387
1388### getFileInfoFromRelativePath<sup>10+</sup>
1389
1390getFileInfoFromRelativePath(relativePath: string) : Promise\<FileInfo>
1391
1392Obtains a **FileInfo** object based on the **relativePath**. This API uses a promise to return the result.
1393
1394**System capability**: SystemCapability.FileManagement.UserFileService
1395
1396**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1397
1398**Parameters**
1399
1400| Name| Type| Mandatory| Description|
1401| --- | --- | --- | -- |
1402| relativePath | string | Yes| Relative path of the file or directory.|
1403
1404**Return value**
1405
1406| Type| Description|
1407| --- | -- |
1408| Promise\<[FileInfo](#fileinfo)> | Promise used to return the **FileInfo** object obtained.|
1409
1410**Example**
1411
1412  ```ts
1413  import { BusinessError } from '@ohos.base';
1414  // In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
1415  // You can use the relativePath obtained.
1416  async function getRelativePath() {
1417    let relativePath: string = "Download/";
1418    try {
1419      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1420      let fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(relativePath);
1421    } catch (err) {
1422      let error: BusinessError = err as BusinessError;
1423      console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message);
1424    }
1425  }
1426  ```
1427
1428### getFileInfoFromRelativePath<sup>10+</sup>
1429
1430getFileInfoFromRelativePath(relativePath: string, callback: AsyncCallback\<FileInfo>) : void
1431
1432Obtains a **FileInfo** object based on the **relativePath**. This API uses an asynchronous callback to return the result.
1433
1434**System capability**: SystemCapability.FileManagement.UserFileService
1435
1436**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1437
1438**Parameters**
1439
1440| Name| Type| Mandatory| Description|
1441| --- | --- | --- | -- |
1442| relativePath | string | Yes| Relative path of the file or directory.|
1443| callback | AsyncCallback&lt;[FileInfo](#fileinfo)&gt; | Yes| Callback invoked to return the **FileInfo** object obtained.|
1444
1445**Example**
1446
1447  ```ts
1448  import { BusinessError } from '@ohos.base';
1449  // In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
1450  // You can use the relativePath obtained.
1451  let relativePath: string = "Download/";
1452  try {
1453    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1454    fileAccessHelper.getFileInfoFromRelativePath(relativePath, (err: BusinessError, fileInfo: fileAccess.FileInfo) => {
1455      if (err) {
1456        console.error("Failed to getFileInfoFromRelativePath in async, errCode:" + err.code + ", errMessage:" + err.message);
1457        return;
1458      }
1459      console.log("getFileInfoFromRelativePath success, fileInfo: " + JSON.stringify(fileInfo));
1460    });
1461  } catch (err) {
1462    let error: BusinessError = err as BusinessError;
1463    console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message);
1464  }
1465  ```
1466
1467### query<sup>10+</sup>
1468
1469query(uri:string, metaJson: string) : Promise&lt;string&gt;
1470
1471Queries the attribute information about a file or directory based on the URI. This API uses a promise to return the result.
1472
1473**System capability**: SystemCapability.FileManagement.UserFileService
1474
1475**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1476
1477**Parameters**
1478
1479| Name  | Type  | Mandatory| Description                                                |
1480| -------- | ------ | ---- | ---------------------------------------------------- |
1481| uri      | string | Yes  | URI of the file or directory (obtained from [FileInfo](#fileinfo)).|
1482| metaJson | string | Yes  | Attribute [FILEKEY](#filekey10) to query.       |
1483
1484**Return value**
1485
1486| Type                 | Description                            |
1487| :-------------------- | :------------------------------- |
1488| Promise&lt;string&gt; | Promised used to return the attribute queried and the value obtained.|
1489
1490**Example**
1491
1492  ```ts
1493  import { BusinessError } from '@ohos.base';
1494  async function getQuery01() {
1495    let imageFileRelativePath: string = "/storage/Users/currentUser/Download/queryTest/image/01.jpg";
1496    let jsonStrSingleRelativepath: string = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
1497    try {
1498      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1499      let fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath);
1500      let queryResult = await fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath);
1501      console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path);
1502    } catch (err) {
1503      let error: BusinessError = err as BusinessError;
1504      console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message);
1505    }
1506  }
1507  ```
1508
1509### query<sup>10+</sup>
1510
1511query(uri:string, metaJson: string, callback: AsyncCallback&lt;string&gt;) : void
1512
1513Queries the attribute information about a file or directory based on the URI. This API uses an asynchronous callback to return the result.
1514
1515**System capability**: SystemCapability.FileManagement.UserFileService
1516
1517**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1518
1519**Parameters**
1520
1521| Name  | Type                       | Mandatory| Description                                                |
1522| -------- | --------------------------- | ---- | ---------------------------------------------------- |
1523| uri      | string | Yes  | URI of the file or directory (obtained from [FileInfo](#fileinfo)).|
1524| metaJson | string | Yes  | Attribute [FILEKEY](#filekey10) to query.       |
1525| callback | AsyncCallback&lt;string&gt; | Yes  | Callback invoked to return the attribute queried and the value obtained.                    |
1526
1527**Example**
1528
1529  ```ts
1530  import { BusinessError } from '@ohos.base';
1531  async function getQuery02() {
1532    let imageFileRelativePath: string = "/storage/Users/currentUser/Download/queryTest/image/01.jpg";
1533    let jsonStrSingleRelativepath: string = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
1534    try {
1535      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1536      let fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath);
1537      fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath, (err: BusinessError, queryResult: string) => {
1538        if (err) {
1539          console.log("query_file_single faf query Failed, errCode:" + err.code + ", errMessage:" + err.message);
1540          return;
1541        }
1542        console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path);
1543      })
1544    } catch (err) {
1545      let error: BusinessError = err as BusinessError;
1546      console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message);
1547    }
1548  }
1549  ```
1550
1551### copy<sup>10+</sup>
1552
1553copy(sourceUri: string, destUri: string, force?: boolean) : Promise&lt;Array&lt;CopyResult&gt;&gt;
1554
1555Copies a file or directory. This API uses a promise to return the result.
1556
1557**System capability**: SystemCapability.FileManagement.UserFileService
1558
1559**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1560
1561**Parameters**
1562
1563| Name   | Type   | Mandatory| Description                                                        |
1564| --------- | ------- | ---- | ------------------------------------------------------------ |
1565| sourceUri | string  | Yes  | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
1566| destUri   | string  | Yes  | URI of the file or folder created, for example, **file://docs/storage/Users/currentUser/Download/test**.       |
1567| force     | boolean | No  | Whether to forcibly overwrite the file with the same name. <br>If **force** is **true**, the file with the same name will be overwritten. If **force** is **false** or not specified, the file with the same name will not be overwritten.|
1568
1569**Return value**
1570
1571| Type                                                   | Description                                                        |
1572| :------------------------------------------------------ | :----------------------------------------------------------- |
1573| Promise&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Promise used to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
1574
1575Example 1: Copy a file with **force** unspecified.
1576
1577  ```ts
1578  import { BusinessError } from '@ohos.base';
1579  // A built-in storage directory is used as an example.
1580  // In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
1581  // You can use the URI obtained.
1582  async function copyFunc01() {
1583    let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1584    let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1585    try {
1586      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1587      let copyResult = await fileAccessHelper.copy(sourceFile, destFile);
1588      if (copyResult.length === 0) {
1589        console.log("copy success");
1590      } else {
1591        for (let i = 0; i < copyResult.length; i++) {
1592          console.error("errCode" + copyResult[i].errCode);
1593          console.error("errMsg" + copyResult[i].errMsg);
1594          console.error("sourceUri" + copyResult[i].sourceUri);
1595          console.error("destUri" + copyResult[i].destUri);
1596        }
1597      }
1598    } catch (err) {
1599      let error: BusinessError = err as BusinessError;
1600      console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1601    }
1602  }
1603  ```
1604
1605Example 2: Copy a file or directory when **force** set to **true**.
1606
1607  ```ts
1608  import { BusinessError } from '@ohos.base';
1609  // A built-in storage directory is used as an example.
1610  // In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
1611  // You can use the URI obtained.
1612  async function copyFunc02() {
1613    let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1614    let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1615    try {
1616      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1617      let copyResult = await fileAccessHelper.copy(sourceFile, destFile, true);
1618      if (copyResult.length === 0) {
1619        console.log("copy success");
1620      } else {
1621        for (let i = 0; i < copyResult.length; i++) {
1622          console.error("errCode" + copyResult[i].errCode);
1623          console.error("errMsg" + copyResult[i].errMsg);
1624          console.error("sourceUri" + copyResult[i].sourceUri);
1625          console.error("destUri" + copyResult[i].destUri);
1626        }
1627      }
1628    } catch (err) {
1629      let error: BusinessError = err as BusinessError;
1630      console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1631    }
1632  }
1633  ```
1634
1635### copy<sup>10+</sup>
1636
1637copy(sourceUri: string, destUri: string, callback: AsyncCallback&lt;Array&lt;CopyResult&gt;&gt;) : void
1638
1639Copies a file or directory. This API uses an asynchronous callback to return the result.
1640
1641**System capability**: SystemCapability.FileManagement.UserFileService
1642
1643**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1644
1645**Parameters**
1646
1647| Name   | Type                                            | Mandatory| Description                                                        |
1648| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
1649| sourceUri | string                                           | Yes  | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
1650| destUri   | string                                           | Yes  | URI of the file or folder created, for example, **file://docs/storage/Users/currentUser/Download/test**.        |
1651| callback  | AsyncCallback&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Yes  | Callback invoked to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
1652
1653**Example**
1654
1655  ```ts
1656  import { BusinessError } from '@ohos.base';
1657  // A built-in storage directory is used as an example.
1658  // In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
1659  // You can use the URI obtained.
1660  let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1661  let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1662  try {
1663  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1664    fileAccessHelper.copy(sourceFile, destFile, async (err: BusinessError, copyResult: Array<fileAccess.CopyResult>) => {
1665      if (err) {
1666        console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message);
1667      }
1668      if (copyResult.length === 0) {
1669        console.log("copy success");
1670      } else {
1671        for (let i = 0; i < copyResult.length; i++) {
1672          console.error("errCode" + copyResult[i].errCode);
1673          console.error("errMsg" + copyResult[i].errMsg);
1674          console.error("sourceUri" + copyResult[i].sourceUri);
1675          console.error("destUri" + copyResult[i].destUri);
1676        }
1677      }
1678    });
1679  } catch (err) {
1680    let error: BusinessError = err as BusinessError;
1681    console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1682  }
1683  ```
1684
1685### copy<sup>10+</sup>
1686
1687copy(sourceUri: string, destUri: string, force: boolean, callback: AsyncCallback&lt;Array&lt;CopyResult&gt;&gt;) : void
1688
1689Copies a file or directory. This API uses an asynchronous callback to return the result.
1690
1691**System capability**: SystemCapability.FileManagement.UserFileService
1692
1693**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1694
1695**Parameters**
1696
1697| Name   | Type                                            | Mandatory| Description                                                        |
1698| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
1699| sourceUri | string                                           | Yes  | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
1700| destUri   | string                                           | Yes  | URI of the file or folder created, for example, **file://docs/storage/Users/currentUser/Download/test**.        |
1701| force     | boolean                                          | Yes  | Whether to forcibly overwrite the file with the same name. <br>If **force** is **true**, the file with the same name will be overwritten. If **force** is **false** or not specified, the file with the same name will not be overwritten.|
1702| callback  | AsyncCallback&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Yes  | Callback invoked to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
1703
1704**Example**
1705
1706  ```ts
1707  import { BusinessError } from '@ohos.base';
1708  // A built-in storage directory is used as an example.
1709  // In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
1710  // You can use the URI obtained.
1711  let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1712  let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1713  try {
1714      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1715    fileAccessHelper.copy(sourceFile, destFile, true, async (err: BusinessError, copyResult: Array<fileAccess.CopyResult>) => {
1716      if (err) {
1717        console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message);
1718      }
1719      if (copyResult.length === 0) {
1720        console.log("copy success");
1721      } else {
1722        for (let i = 0; i < copyResult.length; i++) {
1723          console.error("errCode" + copyResult[i].errCode);
1724          console.error("errMsg" + copyResult[i].errMsg);
1725          console.error("sourceUri" + copyResult[i].sourceUri);
1726          console.error("destUri" + copyResult[i].destUri);
1727        }
1728      }
1729    });
1730  } catch (err) {
1731    let error: BusinessError = err as BusinessError;
1732    console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1733  }
1734  ```
1735
1736### registerObserver<sup>10+</sup>
1737
1738registerObserver(uri: string, notifyForDescendants: boolean, callback: Callback&lt;NotifyMessage&gt;): void
1739
1740Registers a callback to listen for the specified URI. URIs and callbacks can be in many-to-many relationships. You are advised to use one callback to observe one URI.
1741
1742**System capability**: SystemCapability.FileManagement.UserFileService
1743
1744**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1745
1746**Parameters**
1747
1748| Name              | Type                                             | Mandatory| Description                          |
1749| -------------------- | ------------------------------------------------- | ---- | ------------------------------ |
1750| uri                  | string                                            | Yes  | URI of the file or directory to observe.               |
1751| notifyForDescendants | boolean                                           | Yes  | Whether to observe changes of the files in the directory.|
1752| callback             | Callback&lt;[NotifyMessage](#notifymessage10)&gt; | Yes  | Callback invoked to return the notification.                  |
1753
1754**Example 1: Register a callback to listen for a URI.**
1755
1756  ```ts
1757  import { BusinessError } from '@ohos.base';
1758  async function registerObserver01() {
1759    let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
1760    try {
1761      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1762      let dirUri1 = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR1');
1763      let dirUri2 = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR2');
1764      // Two notifications are expected to receive because notifyForDescendants is set to true during registration.
1765      // The URI is 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR1/SUB_FILE', and the event type is NOTIFY_MOVED_FROM.
1766      // The URI is 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR1/SUB_FILE', and the event type is NOTIFY_MOVE_SELF.
1767      const callbackDir1 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1768        if (NotifyMessageDir != undefined) {
1769          console.log('NotifyType: ' + NotifyMessageDir.NotifyType + 'NotifyUri:' + NotifyMessageDir.uri[0]);
1770        } else {
1771          console.error("NotifyMessageDir is undefined");
1772        }
1773      }
1774      // The notification expected to receive is about the NOTIFY_MOVED_TO event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR2/SUB_FILE'.
1775      const callbackDir2 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1776        if (NotifyMessageDir != undefined) {
1777          console.log('NotifyType: ' + NotifyMessageDir.NotifyType + 'NotifyUri:' + NotifyMessageDir.uri[0]);
1778        } else {
1779          console.error("NotifyMessageDir is undefined");
1780        }
1781      }
1782      // The notification expected to receive is about the NOTIFY_MOVE_SELF event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR1/SUB_FILE'.
1783      // The notification expected to receive is about the NOTIFY_MOVED_FROM event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR1/SUB_FILE'.
1784      const callbackFile = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1785        if (NotifyMessageDir != undefined) {
1786          console.log('NotifyType: ' + NotifyMessageDir.NotifyType + 'NotifyUri:' + NotifyMessageDir.uri[0]);
1787        } else {
1788          console.error("NotifyMessageDir is undefined");
1789        }
1790      }
1791      let fileUri = await fileAccessHelper.createFile(dirUri1, 'SUB_FILE');
1792      fileAccessHelper.registerObserver(dirUri1, true, callbackDir1);
1793      fileAccessHelper.registerObserver(dirUri2, true, callbackDir2);
1794      // If the moved file itself is not listened for, the NOTIFY_MOVE_SELF event will not be triggered.
1795      fileAccessHelper.registerObserver(fileUri, true, callbackFile);
1796      let moveFileUri = await fileAccessHelper.move(fileUri, dirUri2);
1797      // Do not unregister the callback immediately after the registration is complete, because the unregistration result may be returned before the notification is returned. If this occurs, the notification wll not be received.
1798      fileAccessHelper.unregisterObserver(dirUri1, callbackDir1);
1799      fileAccessHelper.unregisterObserver(dirUri2, callbackDir2);
1800      fileAccessHelper.unregisterObserver(fileUri, callbackFile);
1801    } catch (err) {
1802      let error: BusinessError = err as BusinessError;
1803      console.error("registerObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
1804    }
1805  }
1806  ```
1807
1808Example 2: Use the same **uri**, **notifyForDescendants**, and **callback** to register repeatedly.
1809
1810  ```ts
1811  import { BusinessError } from '@ohos.base';
1812  async function registerObserver02() {
1813    let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
1814    try {
1815      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1816      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
1817      // The notification expected to receive is about the NOTIFY_ADD event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR/SUB_DIR'.
1818      const callbackDir = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1819        if (NotifyMessageDir != undefined) {
1820          console.log('NotifyType: ' + NotifyMessageDir.NotifyType + 'NotifyUri:' + NotifyMessageDir.uri[0]);
1821        } else {
1822          console.error("NotifyMessageDir is undefined");
1823        }
1824      }
1825      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
1826      // A message is returned indicating that the registration is successful. Repeated registration is reported only in the log.
1827      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
1828      let subDirUri = await fileAccessHelper.mkDir(dirUri, 'SUB_DIR');
1829      // Do not unregister the callback immediately after the registration is complete, because the unregistration result may be returned before the notification is returned. If this occurs, the notification wll not be received.
1830      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
1831    } catch (err) {
1832      let error: BusinessError = err as BusinessError;
1833      console.error("registerObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
1834    }
1835  ```
1836
1837Example 3: Use the same **uri** and **callback** but different **notifyForDescendants** for registration. In this case, **notifyForDescendants** will be reset.
1838
1839  ```ts
1840  import { BusinessError } from '@ohos.base';
1841  async function registerObserver03() {
1842    let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
1843    try {
1844      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1845      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
1846      // The first notification expected to receive is about the NOTIFY_ADD event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR/SUB_FILE_1'.
1847      // No second return is expected.
1848      const callbackDir = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1849        if (NotifyMessageDir != undefined) {
1850          console.log('NotifyType: ' + NotifyMessageDir.NotifyType + 'NotifyUri:' + NotifyMessageDir.uri[0]);
1851        } else {
1852          console.error("NotifyMessageDir is undefined");
1853        }
1854      }
1855      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
1856      let subFile1 = await fileAccessHelper.createFile(dirUri, 'SUB_FILE_1');
1857      // After the registration is successful, change notifyForDescendants to false.
1858      fileAccessHelper.registerObserver(dirUri, false, callbackDir);
1859      let subFile2 = await fileAccessHelper.createFile(dirUri, 'SUB_FILE_2');
1860      // Do not unregister the callback immediately after the registration is complete, because the unregistration result may be returned before the notification is returned. If this occurs, the notification wll not be received.
1861      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
1862    } catch (err) {
1863      let error: BusinessError = err as BusinessError;
1864      console.error("registerObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
1865    }
1866  }
1867  ```
1868
1869### unregisterObserver<sup>10+</sup>
1870
1871 unregisterObserver(uri: string, callback?: Callback&lt;NotifyMessage&gt;): void
1872
1873Unregisters a callback that is used to listen for the specified URI.
1874
1875**System capability**: SystemCapability.FileManagement.UserFileService
1876
1877**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1878
1879**Parameters**
1880
1881| Name  | Type                                             | Mandatory| Description                     |
1882| -------- | ------------------------------------------------- | ---- | ------------------------- |
1883| uri      | string                                            | Yes  | URI of the target file or directory.          |
1884| callback | Callback&lt;[NotifyMessage](#notifymessage10)&gt; | No  | Callback to unregister. If this parameter is not specified, all callbacks of the specified URI will be unregistered.|
1885
1886**Example 1: Deregister a callback of the specified URI.**
1887
1888  ```ts
1889  import { BusinessError } from '@ohos.base';
1890  async function UnregisterObserver01() {
1891    let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
1892    try {
1893      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1894      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
1895      // The notification expected to receive is about the NOTIFY_DELETE event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR'.
1896      const callbackDir = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1897        if (NotifyMessageDir != undefined) {
1898          console.log('NotifyType: ' + NotifyMessageDir.NotifyType + 'NotifyUri:' + NotifyMessageDir.uri[0]);
1899        } else {
1900          console.error("NotifyMessageDir is undefined");
1901        }
1902      }
1903      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
1904      await fileAccessHelper.delete(dirUri);
1905      // Do not unregister the callback immediately after the registration is complete, because the unregistration result may be returned before the notification is returned. If this occurs, the notification wll not be received.
1906      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
1907    } catch (err) {
1908      let error: BusinessError = err as BusinessError;
1909      console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
1910    }
1911  }
1912  ```
1913
1914**Example 2: Repeatedly unregister a callback of the specified URI.**
1915
1916  ```ts
1917  import { BusinessError } from '@ohos.base';
1918  async function UnregisterObserver02() {
1919    let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
1920    try {
1921      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1922      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
1923      // The notification expected to receive is about the NOTIFY_DELETE event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR'.
1924      const callbackDir = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1925        if (NotifyMessageDir != undefined) {
1926          console.log('NotifyType: ' + NotifyMessageDir.NotifyType + 'NotifyUri:' + NotifyMessageDir.uri[0]);
1927        } else {
1928          console.error("NotifyMessageDir is undefined");
1929        }
1930      }
1931      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
1932      await fileAccessHelper.delete(dirUri);
1933      // Do not unregister the callback immediately after the registration is complete, because the unregistration result may be returned before the notification is returned. If this occurs, the notification wll not be received.
1934      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
1935      // If the unregistration fails, throw the error code E_CAN_NOT_FIND_URI.
1936      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
1937    } catch (err) {
1938      let error: BusinessError = err as BusinessError;
1939      console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
1940    }
1941  }
1942  ```
1943
1944**Example 3: Unregister all callbacks of the specified URI.**
1945
1946  ```ts
1947  import { BusinessError } from '@ohos.base';
1948  async function UnregisterObserver03() {
1949    let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
1950    try {
1951      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1952      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
1953      // The notification expected to receive is about the NOTIFY_MOVED_FROM event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR/SUB_FILE'.
1954      // The notification expected to receive is about the NOTIFY_MOVED_TO event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR/RENAME_FILE'.
1955      const callbackDir1 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1956        if (NotifyMessageDir != undefined) {
1957          console.log('NotifyType: ' + NotifyMessageDir.NotifyType + 'NotifyUri:' + NotifyMessageDir.uri[0]);
1958        } else {
1959          console.error("NotifyMessageDir is undefined");
1960        }
1961      }
1962      // No notification is expected to receive.
1963      const callbackDir2 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1964        if (NotifyMessageDir != undefined) {
1965          console.log('NotifyType: ' + NotifyMessageDir.NotifyType + 'NotifyUri:' + NotifyMessageDir.uri[0]);
1966        } else {
1967          console.error("NotifyMessageDir is undefined");
1968        }
1969      }
1970      let fileUri = await fileAccessHelper.createFile(dirUri, 'SUB_FILE');
1971      fileAccessHelper.registerObserver(dirUri, true, callbackDir1);
1972      // The registration does not include the events about the next-level directory.
1973      fileAccessHelper.registerObserver(dirUri, false, callbackDir2);
1974      let renameUri = await fileAccessHelper.rename(fileUri, 'RENAME_FILE');
1975      // Unregister all callbacks (callbackDir1 and callbackDir2) of dirUri.
1976      // Do not unregister the callback immediately after the registration is complete, because the unregistration result may be returned before the notification is returned. If this occurs, the notification wll not be received.
1977      fileAccessHelper.unregisterObserver(dirUri);
1978      await fileAccessHelper.delete(dirUri);
1979    } catch (err) {
1980      let error: BusinessError = err as BusinessError;
1981      console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
1982    }
1983  }
1984  ```
1985
1986## CopyResult<sup>10+</sup>
1987
1988Defines the information returned when the file copy operation fails. If the copy operation is successful, no information is returned.
1989
1990**System capability**: SystemCapability.FileManagement.UserFileService
1991
1992**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1993
1994| Name     | Type  | Readable| Writable| Description               |
1995| --------- | ------ | ---- | ---- | ----------------- |
1996| sourceUri | string | Yes  | No  | URI of the source file or directory.                                        |
1997| destUri   | string | Yes  | No  | URI of the conflict file. If the error is not caused by a conflict, **destUri** is empty.|
1998| errCode   | number | Yes  | No  | Error code.                                                |
1999| errMsg    | string | Yes  | No  | Error information.                                              |
2000
2001## OPENFLAGS
2002
2003Enumerates the file open modes.
2004
2005**Model restriction**: This API can be used only in the stage model.
2006
2007**System capability**: SystemCapability.FileManagement.UserFileService
2008
2009| Name| Value| Description|
2010| ----- | ------ | ------ |
2011| READ | 0o0 | Read mode.|
2012| WRITE | 0o1 | Write mode.|
2013| WRITE_READ | 0o2 | Read/Write mode.|
2014
2015## FILEKEY<sup>10+</sup>
2016
2017Enumerates the keys of the file attributes to query.
2018
2019**Model restriction**: This API can be used only in the stage model.
2020
2021**System capability**: SystemCapability.FileManagement.UserFileService
2022
2023| Name         | Value           | Description                               |
2024| ------------- | ------------- | ----------------------------------- |
2025| DISPLAY_NAME  | 'display_name'  | Name of the file.                             |
2026| DATE_ADDED    | 'date_added'   | Date when the file was created, for example, **1501925454**.     |
2027| DATE_MODIFIED | 'date_modified' | Date when a file was modified, for example, **1665310670**.     |
2028| RELATIVE_PATH | 'relative_path' | Relative path of the file, for example, **Pictures/Screenshots/**.|
2029| FILE_SIZE     | 'size'          | Size of a file, in bytes.       |
2030
2031## NotifyType<sup>10+</sup>
2032
2033Enumerates the notification types.
2034
2035**Model restriction**: This API can be used only in the stage model.
2036
2037**System capability**: SystemCapability.FileManagement.UserFileService
2038
2039| Name             | Value  | Description                                                        |
2040| ----------------- | ---- | ------------------------------------------------------------ |
2041| NOTIFY_ADD        | 0    | File added.<br>See examples 2 and 3 of **registerObserver**.                                                |
2042| NOTIFY_DELETE     | 1    | File deleted.<br>See examples 1 and 2 of **unregisterObserver(uri: string, callback: Callback&lt;NotifyMessage&gt;)**.                                              |
2043| NOTIFY_MOVED_TO   | 2    | File or folder moved in (for example, a file or folder in the target directory is renamed, or a file or folder is moved to the target directory).<br>See example 1 of **registerObserver** and example 1 of **unregisterObserver(uri: string)**.|
2044| NOTIFY_MOVED_FROM | 3    | File or folder moved out (for example, a file or folder in the target directory is renamed and no longer in the target directory, or a file or folder is moved out from the target directory).<br>See example 1 of **registerObserver** and example 1 of **unregisterObserver(uri: string)**.|
2045| NOTIFY_MOVE_SELF  | 4    | File moved (for example, the target file or folder is renamed or moved).<br>See example 1 **registerObserver**.    |
2046
2047## NotifyMessage<sup>10+</sup>
2048
2049Represents the notification message.
2050
2051**Model restriction**: This API can be used only in the stage model.
2052
2053**System capability**: SystemCapability.FileManagement.UserFileService
2054
2055**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2056
2057| Name| Type                       | Readable| Writable| Description                                                     |
2058| ---- | --------------------------- | ---- | ---- | --------------------------------------------------------- |
2059| type | [NotifyType](#notifytype10) | Yes  | No  | Notification type.                                           |
2060| uris | Array&lt;string&gt;         | Yes  | No  | URIs of the changed files. Currently, only one notification is supported. A collection of multiple notifications will be supported in later versions.|
2061