1# @ohos.file.fileAccess (User File Access and Management) (System API)
2
3The **fileAccess** module provides a framework for accessing and operating user files based on [extension](../../application-models/extensionability-overview.md). This module interacts with a variety of file management services, such as the storage management service, and provides a set of unified file access and management interfaces for system applications. The storage management service manages both the directories of the built-in storage and resources on external 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.
9> - Currently, the APIs of this module can be called only by **FilePicker** and **FileManager**.
10
11## Modules to Import
12
13```ts
14import fileAccess from '@ohos.file.fileAccess';
15```
16
17## Constant
18
19Represents a URI used for observing the device online/offline status.
20
21**Model restriction**: This constant can be used only in the stage model.
22
23**System capability**: SystemCapability.FileManagement.UserFileService
24
25**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
26
27| Name| Type                       | Read-Only| Writable| Description                                                     |
28| ---- | --------------------------- | ---- | ---- | --------------------------------------------------------- |
29| DEVICES_URI<sup>11+</sup>  | string | Yes  | No  | URI used for observing the device online/offline status.                   |
30
31## fileAccess.getFileAccessAbilityInfo
32
33getFileAccessAbilityInfo() : Promise&lt;Array&lt;Want&gt;&gt;
34
35Obtains 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.
36
37**Model restriction**: This API can be used only in the stage model.
38
39**System capability**: SystemCapability.FileManagement.UserFileService
40
41**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
42
43**Return value**
44
45| Type| Description|
46| --- | -- |
47| Promise&lt;Array&lt;[Want](../apis-ability-kit/js-apis-app-ability-want.md)&gt;&gt; | Promise used to return the want information obtained.|
48
49**Error codes**
50
51For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
52
53**Example**
54
55  ```ts
56  import { BusinessError } from '@ohos.base';
57  import Want from '@ohos.app.ability.Want';
58  async function getFileAccessAbilityInfo() {
59    let wantInfos: Array<Want> = [];
60    try {
61      wantInfos = await fileAccess.getFileAccessAbilityInfo();
62      console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos));
63    } catch (err) {
64      let error: BusinessError = err as BusinessError;
65      console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message);
66    }
67  }
68  ```
69
70## fileAccess.getFileAccessAbilityInfo
71
72getFileAccessAbilityInfo(callback: AsyncCallback&lt;Array&lt;Want&gt;&gt;): void
73
74Obtains 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.
75
76**Model restriction**: This API can be used only in the stage model.
77
78**System capability**: SystemCapability.FileManagement.UserFileService
79
80**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
81
82**Parameters**
83
84| Name| Type| Mandatory| Description|
85| --- | --- | --- | -- |
86| callback | AsyncCallback&lt;Array&lt;[Want](../apis-ability-kit/js-apis-app-ability-want.md)&gt;&gt; | Yes| Callback used to return the want information obtained.|
87
88**Error codes**
89
90For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
91
92**Example**
93
94  ```ts
95  import { BusinessError } from '@ohos.base';
96  import Want from '@ohos.app.ability.Want';
97  async function getFileAccessAbilityInfo() {
98    try {
99      fileAccess.getFileAccessAbilityInfo((err: BusinessError, wantInfos: Array<Want>) => {
100        if (err) {
101          console.error("Failed to getFileAccessAbilityInfo in async, errCode:" + err.code + ", errMessage:" + err.message);
102          return;
103        }
104        console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos));
105      });
106    } catch (err) {
107      let error: BusinessError = err as BusinessError;
108      console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message);
109    }
110  }
111  ```
112
113## fileAccess.createFileAccessHelper
114
115createFileAccessHelper(context: Context, wants: Array&lt;Want&gt;) : FileAccessHelper
116
117Creates a **Helper** object to bind with the specified Wants. This API returns the result synchronously. The **Helper** object provides file access and management capabilities.
118
119**Model restriction**: This API can be used only in the stage model.
120
121**System capability**: SystemCapability.FileManagement.UserFileService
122
123**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
124
125**Parameters**
126
127| Name| Type| Mandatory| Description|
128| --- | --- | --- | -- |
129| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes| Context of the ability.|
130| wants | Array&lt;[Want](../apis-ability-kit/js-apis-app-ability-want.md)&gt; | Yes| Wants to start the abilities.|
131
132**Return value**
133
134| Type| Description|
135| --- | -- |
136| [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|
137
138**Error codes**
139
140For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
141
142**Example**
143
144  ```ts
145  import { BusinessError } from '@ohos.base';
146  import Want from '@ohos.app.ability.Want';
147  import common from '@ohos.app.ability.common';
148  let context = getContext(this) as common.UIAbilityContext;
149  function createFileAccessHelper01() {
150    let fileAccessHelper: fileAccess.FileAccessHelper;
151    // Obtain wantInfos by using getFileAccessAbilityInfo().
152    let wantInfos: Array<Want> = [
153      {
154        bundleName: "com.ohos.UserFile.ExternalFileManager",
155        abilityName: "FileExtensionAbility",
156      },
157    ]
158    try {
159      // context is passed by EntryAbility.
160      fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos);
161      if (!fileAccessHelper) {
162        console.error("createFileAccessHelper interface returns an undefined object");
163      }
164    } catch (err) {
165      let error: BusinessError = err as BusinessError;
166      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
167    }
168  }
169  ```
170
171## fileAccess.createFileAccessHelper
172
173createFileAccessHelper(context: Context) : FileAccessHelper
174
175Creates a **Helper** object to bind with all file management services in the system. This API returns the result synchronously.
176
177**Model restriction**: This API can be used only in the stage model.
178
179**System capability**: SystemCapability.FileManagement.UserFileService
180
181**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
182
183**Parameters**
184
185| Name| Type| Mandatory| Description|
186| --- | --- | --- | -- |
187| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes| Context of the ability.|
188
189**Return value**
190
191| Type| Description|
192| --- | -- |
193| [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|
194
195**Error codes**
196
197For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
198
199**Example**
200
201  ```ts
202  import { BusinessError } from '@ohos.base';
203  import common from '@ohos.app.ability.common';
204  let context = getContext(this) as common.UIAbilityContext;
205  function createFileAccessHelper02() {
206    let fileAccessHelperAllServer: fileAccess.FileAccessHelper;
207    // Create a Helper object to interact with all file management services configured with fileAccess in the system.
208    try {
209      // context is passed by EntryAbility.
210      fileAccessHelperAllServer = fileAccess.createFileAccessHelper(context);
211      if (!fileAccessHelperAllServer) {
212        console.error("createFileAccessHelper interface returns an undefined object");
213      }
214    } catch (err) {
215      let error: BusinessError = err as BusinessError;
216      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
217    }
218  }
219  ```
220
221## FileInfo
222
223Provides APIs for managing file or folder attribute information.
224
225**Model restriction**: This API can be used only in the stage model.
226
227**System capability**: SystemCapability.FileManagement.UserFileService
228
229**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
230
231### Properties
232
233| Name| Type  | Read-Only| Writable| Description    |
234| ------ | ------ | -------- | ------ | -------- |
235| uri | string | Yes| No| URI of the file or folder.|
236| relativePath<sup>10+</sup> | string | Yes| No| Relative path of the file or folder.|
237| fileName | string | Yes| No| Name of the file or folder.|
238| mode | number | Yes| No| Permissions on the file or folder.|
239| size | number | Yes| No|  Size of the file or folder.|
240| mtime | number | Yes| No|  Time when the file or folder was last modified.|
241| mimeType | string | Yes| No|  Multipurpose Internet Mail Extensions (MIME) type of the file or folder.|
242
243### listFile
244
245listFile(filter?: Filter) : FileIterator
246
247Obtains a **FileIterator** object that lists the next-level files (folders) matching the specified conditions of this directory. This API returns the result synchronously. [FileInfo](#fileinfo) is returned by [next()](#next). Currently, only built-in storage devices support the file filter.
248
249**Model restriction**: This API can be used only in the stage model.
250
251**System capability**: SystemCapability.FileManagement.UserFileService
252
253**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
254
255**Parameters**
256
257| Name| Type| Mandatory| Description|
258| --- | --- | -- | -- |
259| filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object that specifies the conditions for listing files. |
260
261**Return value**
262
263| Type| Description|
264| --- | -- |
265| [FileIterator](#fileiterator) | **FileIterator** object obtained.|
266
267**Error codes**
268
269For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
270
271**Example**
272
273  ```ts
274  import { BusinessError } from '@ohos.base';
275  // fileInfoDir indicates information about a directory.
276  // let filter = { suffix : [".txt", ".jpg", ".xlsx"] };
277  let fileInfoDir :Array<fileAccess.FileInfo> = [];
278  let subfileInfos: Array<fileAccess.FileInfo> = [];
279  let isDone: boolean = false;
280  try {
281    for (let i = 0; i < fileInfoDir.length; ++i) {
282      let fileIterator = fileInfoDir[i].listFile();
283      // listFile() with the filter implementation.
284      // let fileIterator = fileInfoDir.listFile(filter);
285      if (!fileIterator) {
286        console.error("listFile interface returns an undefined object");
287      }
288      while (!isDone) {
289        let result = fileIterator.next();
290        console.log("next result = " + JSON.stringify(result));
291        isDone = result.done;
292        if (!isDone) {
293          subfileInfos.push(result.value);
294        }
295      }
296    }
297  } catch (err) {
298    let error: BusinessError = err as BusinessError;
299    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
300  }
301  ```
302
303### scanFile
304
305scanFile(filter?: Filter) : FileIterator;
306
307Obtains a **FileIterator** object that recursively retrieves the files matching the specified conditions of this directory. This API returns the result synchronously. [FileInfo](#fileinfo) is returned by [next()](#next). Currently, this API supports only built-in storage devices.
308
309**Model restriction**: This API can be used only in the stage model.
310
311**System capability**: SystemCapability.FileManagement.UserFileService
312
313**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
314
315**Parameters**
316
317| Name| Type| Mandatory| Description|
318| --- | --- | -- | -- |
319| filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object that specifies the conditions for listing files. |
320
321**Return value**
322
323| Type| Description|
324| --- | -- |
325| [FileIterator](#fileiterator) | **FileIterator** object obtained.|
326
327**Error codes**
328
329For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
330
331**Example**
332
333  ```ts
334  import { BusinessError } from '@ohos.base';
335  // fileInfoDir indicates information about a directory.
336  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
337  let fileInfoDir: Array<fileAccess.FileInfo> = [];
338  let subfileInfos: Array<fileAccess.FileInfo> = [];
339  let isDone: boolean = false;
340  try {
341    for (let i = 0; i < fileInfoDir.length; ++i) {
342      let fileIterator = fileInfoDir[i].scanFile();
343      // scanFile() with the filter implementation.
344      // let fileIterator = fileInfoDir.scanFile(filter);
345      if (!fileIterator) {
346        console.error("scanFile interface returns an undefined object");
347      }
348      while (!isDone) {
349        let result = fileIterator.next();
350        console.log("next result = " + JSON.stringify(result));
351        isDone = result.done;
352        if (!isDone) {
353          subfileInfos.push(result.value);
354        }
355      }
356    }
357  } catch (err) {
358    let error: BusinessError = err as BusinessError;
359    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
360  }
361  ```
362
363## FileIterator
364
365Provides the **FileIterator** object.
366
367**Model restriction**: This API can be used only in the stage model.
368
369**System capability**: SystemCapability.FileManagement.UserFileService
370
371**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
372
373### next
374
375next() : { value: FileInfo, done: boolean }
376
377Obtains information about the next-level files or folders.
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**Return value**
386
387| Type| Description|
388| --- | -- |
389| {value: [FileInfo](#fileinfo), done: boolean} | File or folder information obtained. This API traverses the directory until **true** is returned. The **value** field contains the file or folder information obtained.|
390
391**Error codes**
392
393For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
394
395## RootInfo
396
397Provides APIs for managing the device's root attribute information.
398
399**Model restriction**: This API can be used only in the stage model.
400
401**System capability**: SystemCapability.FileManagement.UserFileService
402
403**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
404
405### Properties
406
407| Name| Type  | Read-Only| Writable| Description    |
408| ------ | ------ | -------- | ------ | -------- |
409| deviceType | number | Yes| No|Type of the device.|
410| uri | string | Yes| No| Root directory URI of the device.|
411| relativePath<sup>10+</sup> | string | Yes| No| Relative path of the root directory.|
412| displayName | string | Yes| No| Device name.|
413| deviceFlags | number | Yes| No| Capabilities supported by the device.|
414
415### listFile
416
417listFile(filter?: Filter) : FileIterator
418
419Obtains a **FileIterator** object that lists the first-level files (directories) matching the specified conditions from the device root directory. This API returns the result synchronously. [FileInfo](#fileinfo) is return by [next()](#next-1). Currently, only built-in storage devices support the file filter.
420
421**Model restriction**: This API can be used only in the stage model.
422
423**System capability**: SystemCapability.FileManagement.UserFileService
424
425**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
426
427**Parameters**
428
429| Name| Type| Mandatory| Description|
430| --- | --- | -- | -- |
431| filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object that specifies the conditions for listing files. |
432
433**Return value**
434
435| Type| Description|
436| --- | -- |
437| [FileIterator](#fileiterator) | **FileIterator** object obtained.|
438
439**Error codes**
440
441For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
442
443**Example**
444
445  ```ts
446  import { BusinessError } from '@ohos.base';
447  // rootInfo can be obtained by getRoots().
448  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
449  let rootInfo: Array<fileAccess.FileInfo> = [];
450  let fileInfos: Array<fileAccess.FileInfo> = [];
451  let isDone: boolean = false;
452  try {
453    for (let i = 0; i < rootInfo.length; ++i) {
454      let fileIterator = rootInfo[i].listFile();
455      // listFile() with the filter implementation.
456      // let fileIterator = rootInfo.listFile(filter);
457      if (!fileIterator) {
458        console.error("listFile interface returns an undefined object");
459      }
460      while (!isDone) {
461        let result = fileIterator.next();
462        console.log("next result = " + JSON.stringify(result));
463        isDone = result.done;
464        if (!isDone) {
465          fileInfos.push(result.value);
466        }
467      }
468    }
469  } catch (err) {
470    let error: BusinessError = err as BusinessError;
471    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
472  }
473  ```
474
475### scanFile
476
477scanFile(filter?: Filter) : FileIterator
478
479Obtains a **FileIterator** object that recursively retrieves the files matching the specified conditions from the device root directory. This API returns the result synchronously. [FileInfo](#fileinfo) is returned by [next()](#next-1). Currently, this API supports only built-in storage devices.
480
481**Model restriction**: This API can be used only in the stage model.
482
483**System capability**: SystemCapability.FileManagement.UserFileService
484
485**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
486
487**Parameters**
488
489| Name| Type| Mandatory| Description|
490| --- | --- | -- | -- |
491| filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object that specifies the conditions for listing files. |
492
493**Return value**
494
495| Type| Description|
496| --- | -- |
497| [FileIterator](#fileiterator) | **FileIterator** object obtained.|
498
499**Error codes**
500
501For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
502
503**Example**
504
505  ```ts
506  import { BusinessError } from '@ohos.base';
507  // rootInfo can be obtained by getRoots().
508  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
509  let rootInfo: Array<fileAccess.FileInfo> = [];
510  let fileInfos: Array<fileAccess.FileInfo> = [];
511  let isDone: boolean = false;
512  try {
513    for (let i = 0; i < rootInfo.length; ++i) {
514      let fileIterator = rootInfo[i].scanFile();
515      // scanFile with the filter implementation.
516      // let fileIterator = rootInfo.scanFile(filter);
517      if (!fileIterator) {
518        console.error("scanFile interface returns undefined object");
519      }
520      while (!isDone) {
521        let result = fileIterator.next();
522        console.log("next result = " + JSON.stringify(result));
523        isDone = result.done;
524        if (!isDone) {
525          fileInfos.push(result.value);
526        }
527      }
528    }
529  } catch (err) {
530    let error: BusinessError = err as BusinessError;
531    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
532  }
533  ```
534
535## RootIterator
536
537Provides an iterator object of the device root directory.
538
539**Model restriction**: This API can be used only in the stage model.
540
541**System capability**: SystemCapability.FileManagement.UserFileService
542
543**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
544
545### next
546
547next() : { value: RootInfo, done: boolean }
548
549Obtains the next-level root directory.
550
551**Model restriction**: This API can be used only in the stage model.
552
553**System capability**: SystemCapability.FileManagement.UserFileService
554
555**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
556
557**Return value**
558
559| Type| Description|
560| --- | -- |
561| {value: [RootInfo](#rootinfo), done: boolean} | Root directory information obtained. This API traverses the directory until **true** is returned. The **value** field contains the root directory information obtained.|
562
563**Error codes**
564
565For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
566
567## FileAccessHelper
568
569Provides a **FileAccessHelper** object.
570
571**System capability**: SystemCapability.FileManagement.UserFileService
572
573**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
574
575### getRoots
576
577getRoots() : Promise&lt;RootIterator&gt;
578
579Obtains information about the device root nodes of the file management services associated with the **Helper** object. This API uses a promise to return
580a **RootIterator** object. You can use [next](#next-1) to return [RootInfo](#rootinfo).
581
582**System capability**: SystemCapability.FileManagement.UserFileService
583
584**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
585
586**Return value**
587
588| Type| Description|
589| --- | -- |
590| Promise&lt;[RootIterator](#rootiterator)&gt; | Promise used to return a **RootIterator** object.|
591
592**Error codes**
593
594For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
595
596**Example**
597
598  ```ts
599async function getRoots() {
600  let rootIterator: fileAccess.RootIterator;
601  let rootinfos: Array<fileAccess.RootInfo> = [];
602  let isDone: boolean = false;
603  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
604  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
605  try {
606    if (fileAccessHelper != undefined) {
607      rootIterator = await fileAccessHelper.getRoots();
608      if (!rootIterator) {
609        console.error("getRoots interface returns an undefined object");
610      }
611      while (!isDone) {
612        let result = rootIterator.next();
613        console.log("next result = " + JSON.stringify(result));
614        isDone = result.done;
615        if (!isDone) {
616          rootinfos.push(result.value);
617        }
618      }
619    }
620  } catch (err) {
621    let error: BusinessError = err as BusinessError;
622    console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
623  }
624}
625  ```
626
627### getRoots
628
629getRoots(callback:AsyncCallback&lt;RootIterator&gt;) : void
630
631Obtains information about the device root nodes of the file management services associated with the **Helper** object. This API uses an asynchronous callback to return
632a **RootIterator** object. You can use [next](#next-1) to return [RootInfo](#rootinfo).
633
634**System capability**: SystemCapability.FileManagement.UserFileService
635
636**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
637
638**Parameters**
639
640| Name| Type| Mandatory| Description|
641| --- | --- | --- | -- |
642| callback | AsyncCallback&lt;[RootIterator](#rootiterator)&gt; | Yes| Callback used to return a **RootIterator** object.|
643
644**Error codes**
645
646For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
647
648**Example**
649
650  ```ts
651  import { BusinessError } from '@ohos.base';
652  async function getRoots() {
653    let rootinfos: Array<fileAccess.RootInfo> = [];
654    let isDone: boolean = false;
655    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
656    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
657    try {
658      if (fileAccessHelper != undefined) {
659        fileAccessHelper.getRoots((err: BusinessError, rootIterator: fileAccess.RootIterator) => {
660          if (err) {
661            console.error("Failed to getRoots in async, errCode:" + err.code + ", errMessage:" + err.message);
662          }
663          while (!isDone) {
664            let result = rootIterator.next();
665            console.log("next result = " + JSON.stringify(result));
666            isDone = result.done;
667            if (!isDone) {
668              rootinfos.push(result.value);
669            }
670          }
671        });
672      }
673    } catch (err) {
674      let error: BusinessError = err as BusinessError;
675      console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
676    }
677  }
678  ```
679
680### createFile
681
682createFile(uri: string, displayName: string) : Promise&lt;string&gt;
683
684Creates a file in a directory. This API uses a promise to return the result.
685
686**System capability**: SystemCapability.FileManagement.UserFileService
687
688**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
689
690**Parameters**
691
692| Name| Type| Mandatory| Description|
693| --- | --- | --- | -- |
694| uri | string | Yes| URI of the destination directory for the file to create.|
695| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
696
697**Return value**
698
699| Type| Description|
700| --- | -- |
701| Promise&lt;string&gt; | Promise used to return the URI of the file created.|
702
703**Error codes**
704
705For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
706
707**Example**
708
709  ```ts
710  import { BusinessError } from '@ohos.base';
711  async function createFile() {
712    // A built-in storage directory is used as an example.
713    // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
714    // You can use the URI obtained.
715    let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
716    let displayName: string = "file1";
717    let fileUri: string;
718    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
719    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
720    try {
721        if (fileAccessHelper != undefined) {
722        fileUri = await fileAccessHelper.createFile(sourceUri, displayName);
723        if (!fileUri) {
724          console.error("createFile return undefined object");
725          return;
726        }
727        console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri));
728      }
729    } catch (err) {
730      let error: BusinessError = err as BusinessError;
731      console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
732    }
733  }
734  ```
735
736### createFile
737
738createFile(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
739
740Creates a file in a directory. This API uses an asynchronous callback to return the result.
741
742**System capability**: SystemCapability.FileManagement.UserFileService
743
744**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
745
746**Parameters**
747
748| Name| Type| Mandatory| Description|
749| --- | --- | --- | -- |
750| uri | string | Yes| URI of the destination directory for the file to create.|
751| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
752| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the URI of the file created.|
753
754**Error codes**
755
756For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
757
758**Example**
759
760  ```ts
761  import { BusinessError } from '@ohos.base';
762  // A built-in storage directory is used as an example.
763  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
764  // You can use the URI obtained.
765  let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
766  let displayName: string = "file1";
767  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
768  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
769  try {
770    if (fileAccessHelper != undefined) {
771      fileAccessHelper.createFile(sourceUri, displayName, (err: BusinessError, fileUri: string) => {
772        if (err) {
773          console.error("Failed to createFile in async, errCode:" + err.code + ", errMessage:" + err.message);
774        }
775        console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri));
776      });
777    }
778  } catch (err) {
779    let error: BusinessError = err as BusinessError;
780    console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
781  }
782  ```
783
784### mkDir
785
786mkDir(parentUri: string, displayName: string) : Promise&lt;string&gt;
787
788Creates a folder in a directory. This API uses a promise to return the result.
789
790**System capability**: SystemCapability.FileManagement.UserFileService
791
792**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
793
794**Parameters**
795
796| Name| Type| Mandatory| Description|
797| --- | --- | --- | -- |
798| parentUri | string | Yes| URI of the destination directory for the folder to create.|
799| displayName | string | Yes| Name of the folder to create.|
800
801**Return value**
802
803| Type| Description|
804| --- | -- |
805| Promise&lt;string&gt; | Promise used to return the URI of the folder created.|
806
807**Error codes**
808
809For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
810
811**Example**
812
813  ```ts
814  import { BusinessError } from '@ohos.base';
815  // A built-in storage directory is used as an example.
816  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
817  // You can use the URI obtained.
818  async function createDirectory() {
819    let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
820    let dirName: string = "dirTest";
821    let dirUri: string;
822    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
823    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
824    try {
825      if (fileAccessHelper != undefined) {
826        dirUri = await fileAccessHelper.mkDir(sourceUri, dirName);
827        if (!dirUri) {
828          console.error("mkDir return undefined object");
829        } else {
830          console.log("mkDir success, dirUri: " + JSON.stringify(dirUri));
831        }
832      }
833    } catch (err) {
834      let error: BusinessError = err as BusinessError;
835      console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message);
836    }
837  }
838  ```
839
840### mkDir
841
842mkDir(parentUri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
843
844Creates a folder. This API uses an asynchronous callback to return the result.
845
846**System capability**: SystemCapability.FileManagement.UserFileService
847
848**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
849
850**Parameters**
851
852| Name| Type| Mandatory| Description|
853| --- | --- | --- | -- |
854| parentUri | string | Yes| URI of the destination directory for the folder to create.|
855| displayName | string | Yes| Name of the folder to create.|
856| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the URI of the folder created.|
857
858**Error codes**
859
860For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
861
862**Example**
863
864  ```ts
865  import { BusinessError } from '@ohos.base';
866  // A built-in storage directory is used as an example.
867  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
868  // You can use the URI obtained.
869  let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
870  let dirName: string = "dirTest";
871  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
872  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
873  try {
874    if (fileAccessHelper != undefined) {
875      fileAccessHelper.mkDir(sourceUri, dirName, (err: BusinessError, dirUri: string) => {
876        if (err) {
877          console.error("Failed to mkDir in async, errCode:" + err.code + ", errMessage:" + err.message);
878        }
879        console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri));
880      });
881    }
882  } catch (err) {
883    let error: BusinessError = err as BusinessError;
884    console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message);
885  }
886  ```
887
888### openFile
889
890openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;
891
892Opens a file. This API uses a promise to return the result.
893
894**System capability**: SystemCapability.FileManagement.UserFileService
895
896**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
897
898**Parameters**
899
900| Name| Type| Mandatory| Description|
901| --- | --- | --- | -- |
902| uri | string | Yes| URI of the file to open.|
903| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
904
905**Return value**
906
907| Type| Description|
908| --- | -- |
909| Promise&lt;number&gt; | Promise used to return the file descriptor (FD) of the file opened.|
910
911**Error codes**
912
913For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
914
915**Example**
916
917  ```ts
918  import { BusinessError } from '@ohos.base';
919  async function openFile01() {
920    // A built-in storage directory is used as an example.
921    // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
922    // You can use the URI obtained.
923    let targetUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
924    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
925    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
926    try {
927      if (fileAccessHelper != undefined) {
928        let fd = await fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ);
929      }
930    } catch (err) {
931      let error: BusinessError = err as BusinessError;
932      console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message);
933    }
934  }
935  ```
936
937### openFile
938
939openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : void
940
941Opens a file. This API uses an asynchronous callback to return the result.
942
943**System capability**: SystemCapability.FileManagement.UserFileService
944
945**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
946
947**Parameters**
948
949| Name| Type| Mandatory| Description|
950| --- | --- | --- | -- |
951| uri | string | Yes| URI of the file to open.|
952| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
953| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the FD of the file opened.|
954
955**Error codes**
956
957For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
958
959**Example**
960
961  ```ts
962  import { BusinessError } from '@ohos.base';
963  // A built-in storage directory is used as an example.
964  // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
965  // You can use the URI obtained.
966  let targetUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
967  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
968  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
969  try {
970    if (fileAccessHelper != undefined) {
971      fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ, (err: BusinessError, fd: number) => {
972        if (err) {
973          console.error("Failed to openFile in async, errCode:" + err.code + ", errMessage:" + err.message);
974        }
975        console.log("openFile sucess, fd: " + fd);
976      });
977    }
978  } catch (err) {
979    let error: BusinessError = err as BusinessError;
980    console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message);
981  }
982  ```
983
984### delete
985
986delete(uri: string) : Promise&lt;number&gt;
987
988Deletes a file or folder. This API uses a promise to return the result.
989
990**System capability**: SystemCapability.FileManagement.UserFileService
991
992**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
993
994**Parameters**
995
996| Name| Type| Mandatory| Description|
997| --- | --- | --- | -- |
998| uri | string | Yes| URI of the file or folder to delete.|
999
1000**Return value**
1001
1002| Type| Description|
1003| --- | -- |
1004| Promise&lt;number&gt; | Promise used to return the result.|
1005
1006**Error codes**
1007
1008For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
1009
1010**Example**
1011
1012  ```ts
1013  import { BusinessError } from '@ohos.base';
1014  async function deleteFile01() {
1015    // A built-in storage directory is used as an example.
1016    // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
1017    // You can use the URI obtained.
1018    let targetUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1019    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1020    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1021    try {
1022      if (fileAccessHelper != undefined) {
1023        let code = await fileAccessHelper.delete(targetUri);
1024        if (code != 0)
1025          console.error("delete failed, code " + code);
1026      }
1027    } catch (err) {
1028      let error: BusinessError = err as BusinessError;
1029      console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message);
1030    }
1031  }
1032  ```
1033
1034### delete
1035
1036delete(uri: string, callback: AsyncCallback&lt;number&gt;) : void
1037
1038Deletes a file or folder. This API uses an asynchronous callback to return the result.
1039
1040**System capability**: SystemCapability.FileManagement.UserFileService
1041
1042**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1043
1044**Parameters**
1045
1046| Name| Type| Mandatory| Description|
1047| --- | --- | --- | -- |
1048| uri | string | Yes| URI of the file or folder to delete.|
1049| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the result.|
1050
1051**Error codes**
1052
1053For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
1054
1055**Example**
1056
1057  ```ts
1058  import { BusinessError } from '@ohos.base';
1059  // A built-in storage directory is used as an example.
1060  // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
1061  // You can use the URI obtained.
1062  let targetUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1063  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1064  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1065  try {
1066    if (fileAccessHelper != undefined) {
1067      fileAccessHelper.delete(targetUri, (err: BusinessError, code: number) => {
1068        if (err) {
1069          console.error("Failed to delete in async, errCode:" + err.code + ", errMessage:" + err.message);
1070        }
1071        console.log("delete sucess, code: " + code);
1072      });
1073    }
1074  } catch (err) {
1075    let error: BusinessError = err as BusinessError;
1076    console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message);
1077  }
1078  ```
1079
1080### move
1081
1082move(sourceFile: string, destFile: string) : Promise&lt;string&gt;
1083
1084Moves a file or folder. This API uses a promise to return the result. Currently, this API does not support move of files or folders across devices.
1085
1086**System capability**: SystemCapability.FileManagement.UserFileService
1087
1088**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1089
1090**Parameters**
1091
1092| Name| Type| Mandatory| Description|
1093| --- | --- | --- | -- |
1094| sourceFile | string | Yes| URI of the file or folder to move.|
1095| destFile | string | Yes| URI of the destination directory, to which the file or folder is moved.|
1096
1097**Return value**
1098
1099| Type| Description|
1100| ----- | ------ |
1101| Promise&lt;string&gt; | Promise used to return the URI of the file or folder in the destination directory.|
1102
1103**Error codes**
1104
1105For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
1106
1107**Example**
1108
1109  ```ts
1110  import { BusinessError } from '@ohos.base';
1111  async function moveFile01() {
1112    // A built-in storage directory is used as an example.
1113    // In the sample code, sourceFile and destFile indicate the files and directories in the Download directory. The URI is the URI in fileInfo.
1114    // You can use the URI obtained.
1115    let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1116    let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1117    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1118    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1119    try {
1120      if (fileAccessHelper != undefined) {
1121        let fileUri = await fileAccessHelper.move(sourceFile, destFile);
1122        console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
1123      }
1124    } catch (err) {
1125      let error: BusinessError = err as BusinessError;
1126      console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
1127    }
1128  }
1129  ```
1130
1131### move
1132
1133move(sourceFile: string, destFile: string, callback: AsyncCallback&lt;string&gt;) : void
1134
1135Moves a file or folder. This API uses an asynchronous callback to return the result. Currently, this API does not support move of files or folders across devices.
1136
1137**System capability**: SystemCapability.FileManagement.UserFileService
1138
1139**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1140
1141**Parameters**
1142
1143| Name| Type| Mandatory| Description|
1144| --- | --- | --- | -- |
1145| sourceFile | string | Yes| URI of the file or folder to move.|
1146| destFile | string | Yes| URI of the destination directory, to which the file or folder is moved.|
1147| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the URI of the file or folder in the destination directory.|
1148
1149**Error codes**
1150
1151For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
1152
1153**Example**
1154
1155  ```ts
1156  import { BusinessError } from '@ohos.base';
1157  // A built-in storage directory is used as an example.
1158  // In the sample code, sourceFile and destFile indicate the files and directories in the Download directory. The URI is the URI in fileInfo.
1159  // You can use the URI obtained.
1160  let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1161  let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1162  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1163  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1164  try {
1165    if (fileAccessHelper != undefined) {
1166      fileAccessHelper.move(sourceFile, destFile, (err: BusinessError, fileUri: string) => {
1167        if (err) {
1168          console.error("Failed to move in async, errCode:" + err.code + ", errMessage:" + err.message);
1169        }
1170        console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
1171      });
1172    }
1173  } catch (err) {
1174    let error: BusinessError = err as BusinessError;
1175    console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
1176  }
1177  ```
1178
1179### rename
1180
1181rename(uri: string, displayName: string) : Promise&lt;string&gt;
1182
1183Renames a file or folder. This API uses a promise to return the result.
1184
1185**System capability**: SystemCapability.FileManagement.UserFileService
1186
1187**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1188
1189**Parameters**
1190
1191| Name| Type| Mandatory| Description|
1192| --- | --- | --- | -- |
1193| uri | string | Yes| URI of the file or folder to rename.|
1194| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.|
1195
1196**Return value**
1197
1198| Type| Description|
1199| --- | -- |
1200| Promise&lt;string&gt; | Promise used to return the URI of the renamed file or folder.|
1201
1202**Error codes**
1203
1204For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
1205
1206**Example**
1207
1208  ```ts
1209  import { BusinessError } from '@ohos.base';
1210  async function renameFile01() {
1211    // A built-in storage directory is used as an example.
1212    // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
1213    // You can use the URI obtained.
1214    let sourceDir: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1215    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1216    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1217    try {
1218      if (fileAccessHelper != undefined) {
1219        let DestDir = await fileAccessHelper.rename(sourceDir, "testDir");
1220        console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
1221      }
1222    } catch (err) {
1223      let error: BusinessError = err as BusinessError;
1224      console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message);
1225    }
1226  }
1227  ```
1228
1229### rename
1230
1231rename(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
1232
1233Renames a file or folder. This API uses an asynchronous callback to return the result.
1234
1235**System capability**: SystemCapability.FileManagement.UserFileService
1236
1237**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1238
1239**Parameters**
1240
1241| Name| Type| Mandatory| Description|
1242| --- | --- | --- | -- |
1243| uri | string | Yes| URI of the file or folder to rename.|
1244| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.|
1245| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the URI of the renamed file or folder.|
1246
1247**Error codes**
1248
1249For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
1250
1251**Example**
1252
1253  ```ts
1254  import { BusinessError } from '@ohos.base';
1255  // A built-in storage directory is used as an example.
1256  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
1257  // You can use the URI obtained.
1258  let sourceDir: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1259  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1260  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1261  try {
1262    if (fileAccessHelper != undefined) {
1263      fileAccessHelper.rename(sourceDir, "testDir", (err: BusinessError, DestDir: string) => {
1264        if (err) {
1265          console.error("Failed to rename in async, errCode:" + err.code + ", errMessage:" + err.message);
1266        }
1267        console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
1268      });
1269    }
1270  } catch (err) {
1271    let error: BusinessError = err as BusinessError;
1272    console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message);
1273  }
1274  ```
1275
1276### access
1277
1278access(sourceFileUri: string) : Promise&lt;boolean&gt;
1279
1280Checks whether a file or folder exists. This API uses a promise to return the result.
1281
1282**System capability**: SystemCapability.FileManagement.UserFileService
1283
1284**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1285
1286**Parameters**
1287
1288| Name| Type| Mandatory| Description|
1289| --- | --- | --- | -- |
1290| sourceFileUri | string | Yes| URI of the file or folder to check.|
1291
1292**Return value**
1293
1294| Type| Description|
1295| --- | -- |
1296| Promise&lt;boolean&gt; | Promise used to return whether the file or folder exists. The value **true** means the file or folder exists, and the value **false** means the opposite.|
1297
1298**Error codes**
1299
1300For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
1301
1302**Example**
1303
1304  ```ts
1305  import { BusinessError } from '@ohos.base';
1306  // A built-in storage directory is used as an example.
1307  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
1308  // You can use the URI obtained.
1309  async function accessFunc() {
1310    let sourceDir: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1311    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1312    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1313    try {
1314      if (fileAccessHelper != undefined) {
1315        let existJudgment = await fileAccessHelper.access(sourceDir);
1316        if (existJudgment) {
1317          console.log("sourceDir exists");
1318        } else {
1319          console.log("sourceDir does not exist");
1320        }
1321      }
1322    } catch (err) {
1323      let error: BusinessError = err as BusinessError;
1324      console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message);
1325    }
1326  }
1327  ```
1328
1329### access
1330
1331access(sourceFileUri: string, callback: AsyncCallback&lt;boolean&gt;) : void
1332
1333Checks whether a file or folder exists. This API uses an asynchronous callback to return the result.
1334
1335**System capability**: SystemCapability.FileManagement.UserFileService
1336
1337**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1338
1339**Parameters**
1340
1341| Name| Type| Mandatory| Description|
1342| --- | --- | --- | -- |
1343| sourceFileUri | string | Yes| URI of the file or folder to check.|
1344| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return whether the file or folder exists. The value **true** means the file or folder exists, and the value **false** means the opposite.|
1345
1346**Error codes**
1347
1348For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
1349
1350**Example**
1351
1352  ```ts
1353  import { BusinessError } from '@ohos.base';
1354  // A built-in storage directory is used as an example.
1355  // In the sample code, sourceDir indicates a folder in the Download directory. The URI is the URI in fileInfo.
1356  // You can use the URI obtained.
1357  let sourceDir: string = "file://docs/storage/Users/currentUser/Download/test";
1358  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1359  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1360  try {
1361    if (fileAccessHelper != undefined) {
1362      fileAccessHelper.access(sourceDir, (err: BusinessError, existJudgment: boolean) => {
1363        if (err) {
1364          console.error("Failed to access in async, errCode:" + err.code + ", errMessage:" + err.message);
1365          return;
1366        }
1367        if (existJudgment)
1368          console.log("sourceDir exists");
1369        else
1370          console.log("sourceDir does not exist");
1371      });
1372    }
1373  } catch (err) {
1374    let error: BusinessError = err as BusinessError;
1375    console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message);
1376  }
1377  ```
1378
1379### getFileInfoFromUri<sup>10+</sup>
1380
1381getFileInfoFromUri(uri: string) : Promise\<FileInfo>
1382
1383Obtains a **FileInfo** object based on a URI. This API uses a promise to return the result.
1384
1385**System capability**: SystemCapability.FileManagement.UserFileService
1386
1387**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1388
1389**Parameters**
1390
1391| Name| Type| Mandatory| Description|
1392| --- | --- | --- | -- |
1393| uri | string | Yes| URI of the file or folder.|
1394
1395**Return value**
1396
1397| Type| Description|
1398| --- | -- |
1399| Promise\<[FileInfo](#fileinfo)> | Promise used to return the **FileInfo** object obtained.|
1400
1401**Example**
1402
1403  ```ts
1404  import { BusinessError } from '@ohos.base';
1405  // A built-in storage directory is used as an example.
1406  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
1407  // You can use the URI obtained.
1408  async function getUri() {
1409    let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
1410    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1411    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1412    try {
1413      if (fileAccessHelper != undefined) {
1414        let fileInfo = await fileAccessHelper.getFileInfoFromUri(sourceUri);
1415      }
1416    } catch (err) {
1417      let error: BusinessError = err as BusinessError;
1418      console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message);
1419    }
1420  }
1421  ```
1422
1423### getFileInfoFromUri<sup>10+</sup>
1424
1425getFileInfoFromUri(uri: string, callback: AsyncCallback\<FileInfo>) : void
1426
1427Obtains a **FileInfo** object based on a URI. This API uses an asynchronous callback to return the result.
1428
1429**System capability**: SystemCapability.FileManagement.UserFileService
1430
1431**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1432
1433**Parameters**
1434
1435| Name| Type| Mandatory| Description|
1436| --- | --- | --- | -- |
1437| uri | string | Yes| URI of the file or folder.|
1438| callback | AsyncCallback&lt;[FileInfo](#fileinfo)&gt; | Yes| Callback used to return the **FileInfo** object obtained.|
1439
1440**Example**
1441
1442  ```ts
1443  import { BusinessError } from '@ohos.base';
1444  // A built-in storage directory is used as an example.
1445  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
1446  // You can use the URI obtained.
1447  let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
1448  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1449  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1450  try {
1451    if (fileAccessHelper != undefined) {
1452      fileAccessHelper.getFileInfoFromUri(sourceUri, (err: BusinessError, fileInfo: fileAccess.FileInfo) => {
1453        if (err) {
1454          console.error("Failed to getFileInfoFromUri in async, errCode:" + err.code + ", errMessage:" + err.message);
1455          return;
1456        }
1457        console.log("getFileInfoFromUri success, fileInfo: " + JSON.stringify(fileInfo));
1458      });
1459    }
1460  } catch (err) {
1461    let error: BusinessError = err as BusinessError;
1462    console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message);
1463  }
1464  ```
1465
1466
1467### getFileInfoFromRelativePath<sup>10+</sup>
1468
1469getFileInfoFromRelativePath(relativePath: string) : Promise\<FileInfo>
1470
1471Obtains a **FileInfo** object based on a relative path. 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| relativePath | string | Yes| Relative path of the file or folder.|
1482
1483**Return value**
1484
1485| Type| Description|
1486| --- | -- |
1487| Promise\<[FileInfo](#fileinfo)> | Promise used to return the **FileInfo** object obtained.|
1488
1489**Example**
1490
1491  ```ts
1492  import { BusinessError } from '@ohos.base';
1493  // In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
1494  // You can use the relativePath obtained.
1495  async function getRelativePath() {
1496    let relativePath: string = "Download/";
1497    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1498    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1499    try {
1500      if (fileAccessHelper != undefined) {
1501        let fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(relativePath);
1502      }
1503    } catch (err) {
1504      let error: BusinessError = err as BusinessError;
1505      console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message);
1506    }
1507  }
1508  ```
1509
1510### getFileInfoFromRelativePath<sup>10+</sup>
1511
1512getFileInfoFromRelativePath(relativePath: string, callback: AsyncCallback\<FileInfo>) : void
1513
1514Obtains a **FileInfo** object based on a relative path. This API uses an asynchronous callback to return the result.
1515
1516**System capability**: SystemCapability.FileManagement.UserFileService
1517
1518**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1519
1520**Parameters**
1521
1522| Name| Type| Mandatory| Description|
1523| --- | --- | --- | -- |
1524| relativePath | string | Yes| Relative path of the file or folder.|
1525| callback | AsyncCallback&lt;[FileInfo](#fileinfo)&gt; | Yes| Callback used to return the **FileInfo** object obtained.|
1526
1527**Example**
1528
1529  ```ts
1530  import { BusinessError } from '@ohos.base';
1531  // In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
1532  // You can use the relativePath obtained.
1533  let relativePath: string = "Download/";
1534  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1535  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1536  try {
1537    if (fileAccessHelper != undefined) {
1538      fileAccessHelper.getFileInfoFromRelativePath(relativePath, (err: BusinessError, fileInfo: fileAccess.FileInfo) => {
1539        if (err) {
1540          console.error("Failed to getFileInfoFromRelativePath in async, errCode:" + err.code + ", errMessage:" + err.message);
1541          return;
1542        }
1543        console.log("getFileInfoFromRelativePath success, fileInfo: " + JSON.stringify(fileInfo));
1544      });
1545    }
1546  } catch (err) {
1547    let error: BusinessError = err as BusinessError;
1548    console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message);
1549  }
1550  ```
1551
1552### query<sup>10+</sup>
1553
1554query(uri:string, metaJson: string) : Promise&lt;string&gt;
1555
1556Queries the attribute information about a file or folder based on a URI. This API uses a promise to return the result.
1557
1558**System capability**: SystemCapability.FileManagement.UserFileService
1559
1560**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1561
1562**Parameters**
1563
1564| Name  | Type  | Mandatory| Description                                                |
1565| -------- | ------ | ---- | ---------------------------------------------------- |
1566| uri      | string | Yes  | File or folder URI obtained from [FileInfo](#fileinfo).|
1567| metaJson | string | Yes  | Attribute [FILEKEY](#filekey10) to query.       |
1568
1569**Return value**
1570
1571| Type                 | Description                            |
1572| :-------------------- | :------------------------------- |
1573| Promise&lt;string&gt; | Promise used to return the file attribute and the value obtained.|
1574
1575**Example**
1576
1577```ts
1578import { BusinessError } from '@ohos.base';
1579async function getQuery01() {
1580  let imageFileRelativePath: string = "/storage/Users/currentUser/Download/queryTest/image/01.jpg";
1581  let jsonStrSingleRelativepath: string = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
1582  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1583  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1584  try {
1585    if (fileAccessHelper != undefined) {
1586      let fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath);
1587      let queryResult = await fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath);
1588      console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path);
1589    }
1590  } catch (err) {
1591    let error: BusinessError = err as BusinessError;
1592    console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message);
1593  }
1594}
1595```
1596
1597### query<sup>10+</sup>
1598
1599query(uri:string, metaJson: string, callback: AsyncCallback&lt;string&gt;) : void
1600
1601Queries the attribute information about a file or folder based on a URI. This API uses an asynchronous callback to return the result.
1602
1603**System capability**: SystemCapability.FileManagement.UserFileService
1604
1605**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1606
1607**Parameters**
1608
1609| Name  | Type                       | Mandatory| Description                                                |
1610| -------- | --------------------------- | ---- | ---------------------------------------------------- |
1611| uri      | string | Yes  | File or folder URI obtained from [FileInfo](#fileinfo).|
1612| metaJson | string | Yes  | Attribute [FILEKEY](#filekey10) to query.       |
1613| callback | AsyncCallback&lt;string&gt; | Yes  | Callback used to return the file attribute and the value obtained.                    |
1614
1615**Example**
1616
1617```ts
1618import { BusinessError } from '@ohos.base';
1619async function getQuery02() {
1620  let imageFileRelativePath: string = "/storage/Users/currentUser/Download/queryTest/image/01.jpg";
1621  let jsonStrSingleRelativepath: string = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
1622  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1623  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1624  try {
1625    if (fileAccessHelper != undefined) {
1626      let fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath);
1627      fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath, (err: BusinessError, queryResult: string) => {
1628        if (err) {
1629          console.log("query_file_single faf query Failed, errCode:" + err.code + ", errMessage:" + err.message);
1630          return;
1631        }
1632        console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path);
1633      })
1634    }
1635  } catch (err) {
1636    let error: BusinessError = err as BusinessError;
1637    console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message);
1638  }
1639}
1640```
1641
1642### copy<sup>10+</sup>
1643
1644copy(sourceUri: string, destUri: string, force?: boolean) : Promise&lt;Array&lt;CopyResult&gt;&gt;
1645
1646Copies a file or folder. This API uses a promise to return the result.
1647
1648**System capability**: SystemCapability.FileManagement.UserFileService
1649
1650**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1651
1652**Parameters**
1653
1654| Name   | Type   | Mandatory| Description                                                        |
1655| --------- | ------- | ---- | ------------------------------------------------------------ |
1656| sourceUri | string  | Yes  | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
1657| destUri   | string  | Yes  | URI of the file or folder created, for example, **file://docs/storage/Users/currentUser/Download/test**.       |
1658| 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.|
1659
1660**Return value**
1661
1662| Type                                                   | Description                                                        |
1663| :------------------------------------------------------ | :----------------------------------------------------------- |
1664| Promise&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Promise used to return the result. If the file or folder is copied successfully, no information is returned. If the file copy fails, a **copyResult** array is returned.|
1665
1666Example 1: Copy a file with **force** unspecified.
1667
1668```ts
1669import { BusinessError } from '@ohos.base';
1670// A built-in storage directory is used as an example.
1671// 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.
1672// You can use the URI obtained.
1673async function copyFunc01() {
1674  let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1675  let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1676  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1677  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1678  try {
1679    if (fileAccessHelper != undefined) {
1680      let copyResult = await fileAccessHelper.copy(sourceFile, destFile);
1681      if (copyResult.length === 0) {
1682        console.log("copy success");
1683      } else {
1684        for (let i = 0; i < copyResult.length; i++) {
1685          console.error("errCode" + copyResult[i].errCode);
1686          console.error("errMsg" + copyResult[i].errMsg);
1687          console.error("sourceUri" + copyResult[i].sourceUri);
1688          console.error("destUri" + copyResult[i].destUri);
1689        }
1690      }
1691    }
1692  } catch (err) {
1693    let error: BusinessError = err as BusinessError;
1694    console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1695  }
1696}
1697```
1698
1699Example 2: Copy a file or folder when **force** set to **true**.
1700
1701```ts
1702import { BusinessError } from '@ohos.base';
1703// A built-in storage directory is used as an example.
1704// 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.
1705// You can use the URI obtained.
1706async function copyFunc02() {
1707  let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1708  let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1709  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1710  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1711  try {
1712    if (fileAccessHelper != undefined) {
1713      let copyResult = await fileAccessHelper.copy(sourceFile, destFile, true);
1714      if (copyResult.length === 0) {
1715        console.log("copy success");
1716      } else {
1717        for (let i = 0; i < copyResult.length; i++) {
1718          console.error("errCode" + copyResult[i].errCode);
1719          console.error("errMsg" + copyResult[i].errMsg);
1720          console.error("sourceUri" + copyResult[i].sourceUri);
1721          console.error("destUri" + copyResult[i].destUri);
1722        }
1723      }
1724    }
1725  } catch (err) {
1726    let error: BusinessError = err as BusinessError;
1727    console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1728  }
1729}
1730```
1731
1732### copy<sup>10+</sup>
1733
1734copy(sourceUri: string, destUri: string, callback: AsyncCallback&lt;Array&lt;CopyResult&gt;&gt;) : void
1735
1736Copies a file or folder. This API uses an asynchronous callback to return the result.
1737
1738**System capability**: SystemCapability.FileManagement.UserFileService
1739
1740**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1741
1742**Parameters**
1743
1744| Name   | Type                                            | Mandatory| Description                                                        |
1745| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
1746| sourceUri | string                                           | Yes  | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
1747| destUri   | string                                           | Yes  | URI of the file or folder created, for example, **file://docs/storage/Users/currentUser/Download/test**.        |
1748| callback  | AsyncCallback&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Yes  | Callback used to return the result. If the file or folder is copied successfully, no information is returned. If the file copy fails, a **copyResult** array is returned.|
1749
1750**Example**
1751
1752```ts
1753import { BusinessError } from '@ohos.base';
1754// A built-in storage directory is used as an example.
1755// 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.
1756// You can use the URI obtained.
1757let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1758let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1759// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1760let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1761try {
1762  if (fileAccessHelper != undefined) {
1763    fileAccessHelper.copy(sourceFile, destFile, async (err: BusinessError, copyResult: Array<fileAccess.CopyResult>) => {
1764      if (err) {
1765        console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message);
1766      }
1767      if (copyResult.length === 0) {
1768        console.log("copy success");
1769      } else {
1770        for (let i = 0; i < copyResult.length; i++) {
1771          console.error("errCode" + copyResult[i].errCode);
1772          console.error("errMsg" + copyResult[i].errMsg);
1773          console.error("sourceUri" + copyResult[i].sourceUri);
1774          console.error("destUri" + copyResult[i].destUri);
1775        }
1776      }
1777    });
1778  }
1779} catch (err) {
1780  let error: BusinessError = err as BusinessError;
1781  console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1782}
1783```
1784
1785### copy<sup>10+</sup>
1786
1787copy(sourceUri: string, destUri: string, force: boolean, callback: AsyncCallback&lt;Array&lt;CopyResult&gt;&gt;) : void
1788
1789Copies a file or folder. This API uses an asynchronous callback to return the result.
1790
1791**System capability**: SystemCapability.FileManagement.UserFileService
1792
1793**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1794
1795**Parameters**
1796
1797| Name   | Type                                            | Mandatory| Description                                                        |
1798| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
1799| sourceUri | string                                           | Yes  | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
1800| destUri   | string                                           | Yes  | URI of the file or folder created, for example, **file://docs/storage/Users/currentUser/Download/test**.        |
1801| 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.|
1802| callback  | AsyncCallback&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Yes  | Callback used to return the result. If the file or folder is copied successfully, no information is returned. If the file copy fails, a **copyResult** array is returned.|
1803
1804**Example**
1805
1806```ts
1807import { BusinessError } from '@ohos.base';
1808// A built-in storage directory is used as an example.
1809// 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.
1810// You can use the URI obtained.
1811let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1812let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1813// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1814let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1815try {
1816  if (fileAccessHelper != undefined) {
1817    fileAccessHelper.copy(sourceFile, destFile, true, async (err: BusinessError, copyResult: Array<fileAccess.CopyResult>) => {
1818      if (err) {
1819        console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message);
1820      }
1821      if (copyResult.length === 0) {
1822        console.log("copy success");
1823      } else {
1824        for (let i = 0; i < copyResult.length; i++) {
1825          console.error("errCode" + copyResult[i].errCode);
1826          console.error("errMsg" + copyResult[i].errMsg);
1827          console.error("sourceUri" + copyResult[i].sourceUri);
1828          console.error("destUri" + copyResult[i].destUri);
1829        }
1830      }
1831    });
1832  }
1833} catch (err) {
1834  let error: BusinessError = err as BusinessError;
1835  console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1836}
1837```
1838
1839### copyFile<sup>11+</sup>
1840
1841copyFile(sourceUri: string, destUri: string, fileName: string): Promise&lt;string&gt;
1842
1843Copies a file with an alternative file name. This API uses a promise to return the result.
1844
1845**Model restriction**: This API can be used only in the stage model.
1846
1847**System capability**: SystemCapability.FileManagement.UserFileService
1848
1849**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1850
1851**Parameters**
1852
1853| Name   | Type   | Mandatory| Description                                                        |
1854| --------- | ------- | ---- | ------------------------------------------------------------ |
1855| sourceUri | string  | Yes  | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
1856| destUri   | string  | Yes  | URI of the destination directory, for example, **file://docs/storage/Users/currentUser/Download/test**.       |
1857| fileName  | string  | Yes  | File name to use if there is a file with the same name as the source file in the destination directory.|
1858
1859**Return value**
1860
1861| Type                                                   | Description                                                        |
1862| :------------------------------------------------------ | :----------------------------------------------------------- |
1863| Promise&lt;string&gt; | URI of the file generated.|
1864
1865**Example**
1866
1867```ts
1868import { BusinessError } from '@ohos.base';
1869// A built-in storage directory is used as an example.
1870// 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.
1871// You can use the URI obtained.
1872async function copyFunc01() {
1873  let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1874  let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1875  let fileName: string = "2.txt";
1876  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1877  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1878  try {
1879    if (fileAccessHelper != undefined) {
1880      let copyResult = await fileAccessHelper.copyFile(sourceFile, destFile, fileName);
1881      console.log("copyResult uri: " + copyResult);
1882    }
1883  } catch (err) {
1884    let error: BusinessError = err as BusinessError;
1885    console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1886  }
1887}
1888```
1889
1890### copyFile<sup>11+</sup>
1891
1892copyFile(sourceUri: string, destUri: string, fileName: string, callback: AsyncCallback&lt;string&gt;) : void
1893
1894Copies a file with an alternative file name. This API uses an asynchronous callback to return the result.
1895
1896**Model restriction**: This API can be used only in the stage model.
1897
1898**System capability**: SystemCapability.FileManagement.UserFileService
1899
1900**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1901
1902**Parameters**
1903
1904| Name   | Type                                            | Mandatory| Description                                                        |
1905| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
1906| sourceUri | string                                           | Yes  | URI of the file or folder to copy, for example, **file://docs/storage/Users/currentUser/Download/1.txt**. |
1907| destUri   | string                                           | Yes  | URI of the destination directory, for example, **file://docs/storage/Users/currentUser/Download/test**.        |
1908| fileName  | string                                           | Yes  | File name to use if there is a file with the same name as the source file in the destination directory.|
1909| callback  | AsyncCallback&lt;string&gt; | Yes  | URI of the file generated.|
1910
1911**Example**
1912
1913```ts
1914import { BusinessError } from '@ohos.base';
1915// A built-in storage directory is used as an example.
1916// 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.
1917// You can use the URI obtained.
1918let sourceFile: string = "file://docs/storage/Users/currentUser/Download/1.txt";
1919let destFile: string = "file://docs/storage/Users/currentUser/Download/test";
1920let fileName: string = "2.txt";
1921// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1922let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1923try {
1924  if (fileAccessHelper != undefined) {
1925    fileAccessHelper.copyFile(sourceFile, destFile, fileName, async (copyResult: string) => {
1926          console.log("copyResult uri: " + copyResult);
1927    });
1928  }
1929} catch (err) {
1930  let error: BusinessError = err as BusinessError;
1931  console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
1932}
1933```
1934
1935### registerObserver<sup>10+</sup>
1936
1937registerObserver(uri: string, notifyForDescendants: boolean, callback: Callback&lt;NotifyMessage&gt;): void
1938
1939Registers a callback to listen for a URI. URIs and callbacks can be in many-to-many relationships. You are advised to use one callback to listen for one URI.
1940
1941**System capability**: SystemCapability.FileManagement.UserFileService
1942
1943**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1944
1945**Parameters**
1946
1947| Name              | Type                                             | Mandatory| Description                          |
1948| -------------------- | ------------------------------------------------- | ---- | ------------------------------ |
1949| uri                  | string                                            | Yes  | URI of the file or folder to observe.               |
1950| notifyForDescendants | boolean                                           | Yes  | Whether to observe changes of the files in the folder. The value **true** means to observe changes of the files in the folder; the value **false** means the opposite.|
1951| callback             | Callback&lt;[NotifyMessage](#notifymessage10)&gt; | Yes  | Callback used to return the notification.                  |
1952
1953**Example 1: Register a callback to listen for a URI.**
1954
1955```ts
1956import { BusinessError } from '@ohos.base';
1957async function registerObserver01() {
1958  let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
1959  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1960  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
1961  try {
1962    if (fileAccessHelper != undefined) {
1963      let dirUri1 = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR1');
1964      let dirUri2 = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR2');
1965      // Two notifications are expected to receive because notifyForDescendants is set to true during registration.
1966      // The URI is 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR1/SUB_FILE', and the event type is NOTIFY_MOVED_FROM.
1967      // The URI is 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR1/SUB_FILE', and the event type is NOTIFY_MOVE_SELF.
1968      const callbackDir1 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1969        if (NotifyMessageDir != undefined) {
1970          console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
1971        } else {
1972          console.error("NotifyMessageDir is undefined");
1973        }
1974      }
1975      // 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'.
1976      const callbackDir2 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1977        if (NotifyMessageDir != undefined) {
1978          console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
1979        } else {
1980          console.error("NotifyMessageDir is undefined");
1981        }
1982      }
1983      // 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'.
1984      // 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'.
1985      const callbackFile = (NotifyMessageDir: fileAccess.NotifyMessage) => {
1986        if (NotifyMessageDir != undefined) {
1987          console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
1988        } else {
1989          console.error("NotifyMessageDir is undefined");
1990        }
1991      }
1992      let fileUri = await fileAccessHelper.createFile(dirUri1, 'SUB_FILE');
1993      fileAccessHelper.registerObserver(dirUri1, true, callbackDir1);
1994      fileAccessHelper.registerObserver(dirUri2, true, callbackDir2);
1995      // If the moved file itself is not listened for, the NOTIFY_MOVE_SELF event will not be triggered.
1996      fileAccessHelper.registerObserver(fileUri, true, callbackFile);
1997      let moveFileUri = await fileAccessHelper.move(fileUri, dirUri2);
1998      // 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.
1999      fileAccessHelper.unregisterObserver(dirUri1, callbackDir1);
2000      fileAccessHelper.unregisterObserver(dirUri2, callbackDir2);
2001      fileAccessHelper.unregisterObserver(fileUri, callbackFile);
2002    }
2003  } catch (err) {
2004    let error: BusinessError = err as BusinessError;
2005    console.error("registerObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
2006  }
2007}
2008```
2009
2010Example 2: Use the same **uri**, **notifyForDescendants**, and **callback** to register repeatedly.
2011
2012```ts
2013import { BusinessError } from '@ohos.base';
2014async function registerObserver02() {
2015  let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
2016  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2017  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2018  try {
2019    if (fileAccessHelper != undefined) {
2020      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
2021      // The notification expected to receive is about the NOTIFY_ADD event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR/SUB_DIR'.
2022      const callbackDir = (NotifyMessageDir: fileAccess.NotifyMessage) => {
2023        if (NotifyMessageDir != undefined) {
2024          console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
2025        } else {
2026          console.error("NotifyMessageDir is undefined");
2027        }
2028      }
2029      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
2030      // A message is returned indicating that the registration is successful. Repeated registration is reported only in the log.
2031      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
2032      let subDirUri = await fileAccessHelper.mkDir(dirUri, 'SUB_DIR');
2033      // 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.
2034      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
2035    }
2036  } catch (err) {
2037    let error: BusinessError = err as BusinessError;
2038    console.error("registerObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
2039  }
2040}
2041```
2042
2043Example 3: Use the same **uri** and **callback** but different **notifyForDescendants** for registration. In this case, **notifyForDescendants** will be reset.
2044
2045```ts
2046import { BusinessError } from '@ohos.base';
2047async function registerObserver03() {
2048  let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
2049  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2050  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2051  try {
2052    if (fileAccessHelper != undefined) {
2053      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
2054      // 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'.
2055      // No second return is expected.
2056      const callbackDir = (NotifyMessageDir: fileAccess.NotifyMessage) => {
2057        if (NotifyMessageDir != undefined) {
2058          console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
2059        } else {
2060          console.error("NotifyMessageDir is undefined");
2061        }
2062      }
2063      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
2064      let subFile1 = await fileAccessHelper.createFile(dirUri, 'SUB_FILE_1');
2065      // After the registration is successful, change notifyForDescendants to false.
2066      fileAccessHelper.registerObserver(dirUri, false, callbackDir);
2067      let subFile2 = await fileAccessHelper.createFile(dirUri, 'SUB_FILE_2');
2068      // 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.
2069      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
2070    }
2071  } catch (err) {
2072    let error: BusinessError = err as BusinessError;
2073    console.error("registerObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
2074  }
2075}
2076```
2077
2078Example 4: Observe the device online/offline status.
2079
2080```ts
2081import { BusinessError } from '@ohos.base';
2082async function UnregisterObserver03() {
2083  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2084  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2085  try {
2086    const callbackDir1 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
2087      if (NotifyMessageDir != undefined) {
2088        console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
2089      } else {
2090        console.error("NotifyMessageDir is undefined");
2091      }
2092    }
2093    if (fileAccessHelper != undefined) {
2094      // Subscribe to the device online/offline status.
2095      fileAccessHelper.registerObserver(fileAccess.DEVICES_URI, true, callbackDir1);
2096      // Unsubscribe from the device online/offline status.
2097      fileAccessHelper.unregisterObserver(fileAccess.DEVICES_URI);
2098    }
2099  } catch (err) {
2100    let error: BusinessError = err as BusinessError;
2101    console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
2102  }
2103}
2104```
2105
2106### unregisterObserver<sup>10+</sup>
2107
2108 unregisterObserver(uri: string, callback?: Callback&lt;NotifyMessage&gt;): void
2109
2110Unregisters a callback that is used to listen for the specified URI.
2111
2112**System capability**: SystemCapability.FileManagement.UserFileService
2113
2114**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2115
2116**Parameters**
2117
2118| Name  | Type                                             | Mandatory| Description                     |
2119| -------- | ------------------------------------------------- | ---- | ------------------------- |
2120| uri      | string                                            | Yes  | URI of the file or folder.          |
2121| 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.|
2122
2123Example 1: Unregister a callback of the specified URI.
2124
2125```ts
2126import { BusinessError } from '@ohos.base';
2127async function UnregisterObserver01() {
2128  let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
2129  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2130  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2131  try {
2132    if (fileAccessHelper != undefined) {
2133      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
2134      // The notification expected to receive is about the NOTIFY_DELETE event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR'.
2135      const callbackDir = (NotifyMessageDir: fileAccess.NotifyMessage) => {
2136        if (NotifyMessageDir != undefined) {
2137          console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
2138        } else {
2139          console.error("NotifyMessageDir is undefined");
2140        }
2141      }
2142      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
2143      await fileAccessHelper.delete(dirUri);
2144      // 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.
2145      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
2146    }
2147  } catch (err) {
2148    let error: BusinessError = err as BusinessError;
2149    console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
2150  }
2151}
2152```
2153
2154Example 2: Repeatedly unregister a callback of the specified URI.
2155
2156```ts
2157import { BusinessError } from '@ohos.base';
2158async function UnregisterObserver02() {
2159  let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
2160  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2161  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2162  try {
2163      if (fileAccessHelper != undefined) {
2164      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
2165      // The notification expected to receive is about the NOTIFY_DELETE event of the URI 'file://docs/storage/Users/currentUser/Documents/NOTIFY_DIR'.
2166      const callbackDir = (NotifyMessageDir: fileAccess.NotifyMessage) => {
2167        if (NotifyMessageDir != undefined) {
2168          console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
2169        } else {
2170          console.error("NotifyMessageDir is undefined");
2171        }
2172      }
2173      fileAccessHelper.registerObserver(dirUri, true, callbackDir);
2174      await fileAccessHelper.delete(dirUri);
2175      // 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.
2176      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
2177      // If the unregistration fails, throw the error code E_CAN_NOT_FIND_URI.
2178      fileAccessHelper.unregisterObserver(dirUri, callbackDir);
2179      }
2180  } catch (err) {
2181    let error: BusinessError = err as BusinessError;
2182    console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
2183  }
2184}
2185```
2186
2187Example 3: Unregister all callbacks of the specified URI.
2188
2189```ts
2190import { BusinessError } from '@ohos.base';
2191async function UnregisterObserver03() {
2192  let DirUri: string = 'file://docs/storage/Users/currentUser/Documents';
2193  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2194  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2195  try {
2196    if (fileAccessHelper != undefined) {
2197      let dirUri = await fileAccessHelper.mkDir(DirUri, 'NOTIFY_DIR');
2198      // 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'.
2199      // 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'.
2200      const callbackDir1 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
2201        if (NotifyMessageDir != undefined) {
2202          console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
2203        } else {
2204          console.error("NotifyMessageDir is undefined");
2205        }
2206      }
2207      // No notification is expected to receive.
2208      const callbackDir2 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
2209        if (NotifyMessageDir != undefined) {
2210          console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
2211        } else {
2212          console.error("NotifyMessageDir is undefined");
2213        }
2214      }
2215      let fileUri = await fileAccessHelper.createFile(dirUri, 'SUB_FILE');
2216      fileAccessHelper.registerObserver(dirUri, true, callbackDir1);
2217      // The registration does not include the events about the next-level directory.
2218      fileAccessHelper.registerObserver(dirUri, false, callbackDir2);
2219      let renameUri = await fileAccessHelper.rename(fileUri, 'RENAME_FILE');
2220      // Unregister all callbacks (callbackDir1 and callbackDir2) of dirUri.
2221      // 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.
2222      fileAccessHelper.unregisterObserver(dirUri);
2223      await fileAccessHelper.delete(dirUri);
2224    }
2225  } catch (err) {
2226    let error: BusinessError = err as BusinessError;
2227    console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
2228  }
2229}
2230```
2231
2232Example 4: Unregistger the device online/offline status.
2233
2234```ts
2235import { BusinessError } from '@ohos.base';
2236async function UnregisterObserver03() {
2237  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2238  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2239  try {
2240    const callbackDir1 = (NotifyMessageDir: fileAccess.NotifyMessage) => {
2241      if (NotifyMessageDir != undefined) {
2242        console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]);
2243      } else {
2244        console.error("NotifyMessageDir is undefined");
2245      }
2246    }
2247    if (fileAccessHelper != undefined) {
2248      // Subscribe to the device online/offline status.
2249      fileAccessHelper.registerObserver(fileAccess.DEVICES_URI, true, callbackDir1);
2250      // Unsubscribe from the device online/offline status.
2251      fileAccessHelper.unregisterObserver(fileAccess.DEVICES_URI);
2252    }
2253  } catch (err) {
2254    let error: BusinessError = err as BusinessError;
2255    console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message);
2256  }
2257}
2258```
2259
2260### moveItem<sup>11+</sup>
2261
2262moveItem(sourceUri: string, destUri: string, force?: boolean) : Promise&lt;Array&lt;MoveResult&gt;&gt;
2263
2264Moves a file or folder. This API uses a promise to return the result.
2265
2266You can forcibly overwrite the file with the same name in the destination directory.
2267
2268Currently, this API does not support move of files or folders across devices.
2269
2270**Model restriction**: This API can be used only in the stage model.
2271
2272**System capability**: SystemCapability.FileManagement.UserFileService
2273
2274**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2275
2276**Parameters**
2277
2278| Name   | Type   | Mandatory| Description                                                        |
2279| --------- | ------- | ---- | ------------------------------------------------------------ |
2280| sourceUri | string  | Yes  | URI of the file or folder to move.                                   |
2281| destUri   | string  | Yes  | URI of the destination directory, to which the file or folder is moved.                                           |
2282| force     | boolean | No  | Whether to forcibly overwrite the file with the same name. The value **true** means to overwrite the file forcibly; the value **false** means the opposite. The default value is **false**.|
2283
2284**Return value**
2285
2286| Type                                                   | Description                                                        |
2287| ------------------------------------------------------- | ------------------------------------------------------------ |
2288| Promise&lt;Array&lt;[MoveResult](#moveresult11)&gt;&gt; | Promise used to return the result. If the operation is successful, no information is returned. If the operation fails, a **MoveResult** array is returned.|
2289
2290**Error codes**
2291
2292For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
2293
2294Example 1: Move a file with **force** unspecified.
2295
2296```ts
2297import { BusinessError } from '@ohos.base';
2298// A built-in storage directory is used as an example.
2299// 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.
2300// You can use the URI obtained.
2301async function moveItemFunc01() {
2302  let sourceUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
2303  let destUri: string = "file://docs/storage/Users/currentUser/Download/test";
2304  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2305  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2306  try {
2307    if (fileAccessHelper != undefined) {
2308      let moveResult = await fileAccessHelper.moveItem(sourceUri, destUri);
2309      if (moveResult.length === 0) {
2310        console.log("moveItem success");
2311      } else {
2312        for (let i = 0; i < moveResult.length; i++) {
2313          console.error("errCode" + moveResult[i].errCode);
2314          console.error("errMsg" + moveResult[i].errMsg);
2315          console.error("sourceUri" + moveResult[i].sourceUri);
2316          console.error("destUri" + moveResult[i].destUri);
2317        }
2318      }
2319    }
2320  } catch (err) {
2321    let error: BusinessError = err as BusinessError;
2322    console.error("moveItem failed, errCode:" + error.code + ", errMessage:" + error.message);
2323  }
2324}
2325```
2326
2327Example 2: Move a file or folder when **force** set to **true**.
2328
2329```ts
2330import { BusinessError } from '@ohos.base';
2331// A built-in storage directory is used as an example.
2332// 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.
2333// You can use the URI obtained.
2334async function moveItemFunc02() {
2335  let sourceUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
2336  let destUri: string = "file://docs/storage/Users/currentUser/Download/test";
2337  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2338  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2339  try {
2340    if (fileAccessHelper != undefined) {
2341      let moveResult = await fileAccessHelper.moveItem(sourceUri, destUri, true);
2342      if (moveResult.length === 0) {
2343        console.log("moveItem success");
2344      } else {
2345        for (let i = 0; i < moveResult.length; i++) {
2346          console.error("errCode" + moveResult[i].errCode);
2347          console.error("errMsg" + moveResult[i].errMsg);
2348          console.error("sourceUri" + moveResult[i].sourceUri);
2349          console.error("destUri" + moveResult[i].destUri);
2350        }
2351      }
2352    }
2353  } catch (err) {
2354    let error: BusinessError = err as BusinessError;
2355    console.error("moveItem failed, errCode:" + error.code + ", errMessage:" + error.message);
2356  }
2357}
2358```
2359
2360### moveItem<sup>11+</sup>
2361
2362moveItem(sourceUri: string, destUri: string, callback: AsyncCallback&lt;Array&lt;MoveResult&gt;&gt;) : void
2363
2364Moves a file or folder. This API uses an asynchronous callback to return the result.
2365
2366Currently, this API does not support move of files or folders across devices.
2367
2368**Model restriction**: This API can be used only in the stage model.
2369
2370**System capability**: SystemCapability.FileManagement.UserFileService
2371
2372**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2373
2374**Parameters**
2375
2376| Name   | Type                                                        | Mandatory| Description                                                        |
2377| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2378| sourceUri | string                                                       | Yes  | URI of the file or folder to move.                                   |
2379| destUri   | string                                                       | Yes  | URI of the destination directory, to which the file or folder is moved.                                           |
2380| callback  | AsyncCallback&lt;Array&lt;[MoveResult](#moveresult11)&gt;&gt; | Yes  | Callback used to return the result. If the operation is successful, no information is returned. If the operation fails, a **moveResult** array is returned.|
2381
2382**Example**
2383
2384```ts
2385import { BusinessError } from '@ohos.base';
2386// A built-in storage directory is used as an example.
2387// 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.
2388// You can use the URI obtained.
2389let sourceUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
2390let destUri: string = "file://docs/storage/Users/currentUser/Download/test";
2391// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2392let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2393try {
2394  if (fileAccessHelper != undefined) {
2395    fileAccessHelper.moveItem(sourceUri, destUri, async (err: BusinessError, copyResult: Array<fileAccess.MoveResult>) => {
2396      if (err) {
2397        console.error("moveItem failed, errCode:" + err.code + ", errMessage:" + err.message);
2398      }
2399      if (moveResult.length === 0) {
2400        console.log("moveItem success");
2401      } else {
2402        for (let i = 0; i < moveResult.length; i++) {
2403          console.error("errCode" + moveResult[i].errCode);
2404          console.error("errMsg" + moveResult[i].errMsg);
2405          console.error("sourceUri" + moveResult[i].sourceUri);
2406          console.error("destUri" + moveResult[i].destUri);
2407        }
2408      }
2409    });
2410  }
2411} catch (err) {
2412  let error: BusinessError = err as BusinessError;
2413  console.error("moveItem failed, errCode:" + error.code + ", errMessage:" + error.message);
2414}
2415```
2416
2417### moveItem<sup>11+</sup>
2418
2419moveItem(sourceUri: string, destUri: string, force: boolean, callback: AsyncCallback&lt;Array&lt;MoveResult&gt;&gt;) : void
2420
2421Moves a file or folder with the specified mode. This API uses an asynchronous callback to return the result.
2422
2423If a file with the same name exists in the destination directory, you can forcibly overwrite the file.
2424
2425Currently, this API does not support move of files or folders across devices.
2426
2427**Model restriction**: This API can be used only in the stage model.
2428
2429**System capability**: SystemCapability.FileManagement.UserFileService
2430
2431**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2432
2433**Parameters**
2434
2435| Name   | Type                                                        | Mandatory| Description                                                        |
2436| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2437| sourceUri | string                                                       | Yes  | URI of the file or folder to move.                                   |
2438| destUri   | string                                                       | Yes  | URI of the destination directory, to which the file or folder is moved.                                           |
2439| force     | boolean                                                      | Yes  | Whether to forcibly overwrite the file with the same name. The value **true** means to overwrite the file forcibly; the value **false** means the opposite. The default value is **false**.|
2440| callback  | AsyncCallback&lt;Array&lt;[MoveResult](#moveresult11)&gt;&gt; | Yes  | Callback used to return the result. If the operation is successful, no information is returned. If the operation fails, a **moveResult** array is returned.|
2441
2442**Example**
2443
2444```ts
2445import { BusinessError } from '@ohos.base';
2446// A built-in storage directory is used as an example.
2447// 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.
2448// You can use the URI obtained.
2449let sourceUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
2450let destUri: string = "file://docs/storage/Users/currentUser/Download/test";
2451// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2452let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2453try {
2454  if (fileAccessHelper != undefined) {
2455    fileAccessHelper.moveItem(sourceUri, destUri, true, async (err: BusinessError, moveResult: Array<fileAccess.MoveResult>) => {
2456      if (err) {
2457        console.error("moveItem failed, errCode:" + err.code + ", errMessage:" + err.message);
2458      }
2459      if (moveResult.length === 0) {
2460        console.log("copy success");
2461      } else {
2462        for (let i = 0; i < moveResult.length; i++) {
2463          console.error("errCode" + moveResult[i].errCode);
2464          console.error("errMsg" + moveResult[i].errMsg);
2465          console.error("sourceUri" + moveResult[i].sourceUri);
2466          console.error("destUri" + moveResult[i].destUri);
2467        }
2468      }
2469    });
2470  }
2471} catch (err) {
2472  let error: BusinessError = err as BusinessError;
2473  console.error("moveItem failed, errCode:" + error.code + ", errMessage:" + error.message);
2474}
2475```
2476
2477### moveFile<sup>11+</sup>
2478
2479moveFile(sourceUri: string, destUri: string, fileName: string) : Promise&lt;string&gt;
2480
2481Moves a file, and renames it if a file with the same name already exists in the destination directory. This API uses a promise to return the result.
2482
2483
2484Currently, this API does not support move of files across devices.
2485
2486**Model restriction**: This API can be used only in the stage model.
2487
2488**System capability**: SystemCapability.FileManagement.UserFileService
2489
2490**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2491
2492**Parameters**
2493
2494| Name    | Type  | Mandatory| Description               |
2495| ---------- | ------ | ---- | ------------------- |
2496| sourceFile | string | Yes  | URI of the file to move.|
2497| destFile   | string | Yes  | URI of the destination directory, to which the file is moved.  |
2498| fileName   | string | Yes  | New name of the file. |
2499
2500**Return value**
2501
2502| Type                 | Description               |
2503| --------------------- | ------------------- |
2504| Promise&lt;string&gt; | Promise used to return the URI of the file in the destination directory.|
2505
2506**Error codes**
2507
2508For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
2509
2510**Example**
2511
2512  ```ts
2513  import { BusinessError } from '@ohos.base';
2514  async function moveFile01() {
2515    // A built-in storage directory is used as an example.
2516    // In the sample code, sourceUri and destUri indicate the files or directories in the Download directory. The URI is the URI in fileInfo.
2517    // You can use the URI obtained.
2518    let sourceUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
2519    let destUri: string = "file://docs/storage/Users/currentUser/Download/test";
2520    let fileName: string;
2521    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2522    let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2523    try {
2524    if (fileAccessHelper != undefined) {
2525        let fileUri = await fileAccessHelper.moveFile(sourceUri, destUri, fileName);
2526        console.log("moveFile sucess, fileUri: " + JSON.stringify(fileUri));
2527    }
2528    } catch (err) {
2529      let error: BusinessError = err as BusinessError;
2530      console.error("moveFile failed, errCode:" + error.code + ", errMessage:" + error.message);
2531    }
2532  }
2533  ```
2534
2535### moveFile<sup>11+</sup>
2536
2537moveFile(sourceUri: string, destUri: string,  fileName: string, callback: AsyncCallback&lt;string&gt;) : void
2538
2539Moves a file, and renames it if a file with the same name already exists in the destination directory. This API uses an asynchronous callback to return the result.
2540
2541
2542
2543Currently, this API does not support move of files across devices.
2544
2545**Model restriction**: This API can be used only in the stage model.
2546
2547**System capability**: SystemCapability.FileManagement.UserFileService
2548
2549**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2550
2551**Parameters**
2552
2553| Name    | Type                       | Mandatory| Description                 |
2554| ---------- | --------------------------- | ---- | --------------------- |
2555| sourceFile | string                      | Yes  | URI of the file to move.|
2556| destFile   | string                      | Yes  | URI of the destination directory, to which the file is moved.    |
2557| fileName   | string                      | Yes  | New name of the file.   |
2558| callback   | AsyncCallback&lt;string&gt; | Yes  | Callback used to return the URI of the file in the destination directory.  |
2559
2560**Error codes**
2561
2562For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).
2563
2564**Example**
2565
2566  ```ts
2567  import { BusinessError } from '@ohos.base';
2568  // A built-in storage directory is used as an example.
2569  // In the sample code, sourceUri and destUri indicate the files or directories in the Download directory. The URI is the URI in fileInfo.
2570  // You can use the URI obtained.
2571  let sourceUri: string = "file://docs/storage/Users/currentUser/Download/1.txt";
2572  let destUri: string = "file://docs/storage/Users/currentUser/Download/test";
2573  let fileName: string;
2574  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
2575  let fileAccessHelper : fileAccess.FileAccessHelper|undefined;
2576  try {
2577    if (fileAccessHelper != undefined) {
2578      fileAccessHelper.moveFile(sourceUri, destUri, fileName, (err: BusinessError, fileUri: string) => {
2579        if (err) {
2580          console.error("Failed to moveFile in async, errCode:" + err.code + ", errMessage:" + err.message);
2581        }
2582        console.log("moveFile sucess, fileUri: " + JSON.stringify(fileUri));
2583      });
2584    }
2585  } catch (err) {
2586    let error: BusinessError = err as BusinessError;
2587    console.error("moveFile failed, errCode:" + error.code + ", errMessage:" + error.message);
2588  }
2589  ```
2590
2591## CopyResult<sup>10+</sup>
2592
2593Defines the information returned when the file copy operation fails. If the copy operation is successful, no information is returned.
2594
2595**System capability**: SystemCapability.FileManagement.UserFileService
2596
2597**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2598
2599| Name     | Type  | Read-Only| Writable| Description               |
2600| --------- | ------ | ---- | ---- | ----------------- |
2601| sourceUri | string | Yes  | No  | URI of the source file or folder.                                        |
2602| destUri   | string | Yes  | No  | URI of the conflicting file. If the error is not caused by a conflict, **destUri** is empty.|
2603| errCode   | number | Yes  | No  | Error code.                                                |
2604| errMsg    | string | Yes  | No  | Error information.                                              |
2605
2606## OPENFLAGS
2607
2608Enumerates the file open modes.
2609
2610**Model restriction**: This API can be used only in the stage model.
2611
2612**System capability**: SystemCapability.FileManagement.UserFileService
2613
2614| Name| Value| Description|
2615| ----- | ------ | ------ |
2616| READ | 0o0 | Read mode.|
2617| WRITE | 0o1 | Write mode.|
2618| WRITE_READ | 0o2 | Read/Write mode.|
2619
2620## FILEKEY<sup>10+</sup>
2621
2622Enumerates the keys of the file attributes to query.
2623
2624**Model restriction**: This API can be used only in the stage model.
2625
2626**System capability**: SystemCapability.FileManagement.UserFileService
2627
2628| Name         | Value           | Description                               |
2629| ------------- | ------------- | ----------------------------------- |
2630| DISPLAY_NAME  | 'display_name'  | Name of the file.                             |
2631| DATE_ADDED    | 'date_added'   | Date when the file was created, for example, **1501925454**.     |
2632| DATE_MODIFIED | 'date_modified' | Date when the file was modified, for example, **1665310670**.     |
2633| RELATIVE_PATH | 'relative_path' | Relative path of the file, for example, **Pictures/Screenshots/**.|
2634| FILE_SIZE     | 'size'          | Size of the file, in bytes.       |
2635
2636## NotifyType<sup>10+</sup>
2637
2638Enumerates the notification types.
2639
2640**Model restriction**: This API can be used only in the stage model.
2641
2642**System capability**: SystemCapability.FileManagement.UserFileService
2643
2644| Name             | Value  | Description                                                        |
2645| ----------------- | ---- | ------------------------------------------------------------ |
2646| NOTIFY_ADD        | 0    | File added.<br>See examples 2 and 3 of **registerObserver**.                                                |
2647| NOTIFY_DELETE     | 1    | File deleted.<br>See examples 1 and 2 of **unregisterObserver(uri: string, callback: Callback&lt;NotifyMessage&gt;)**.                                              |
2648| 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)**.|
2649| 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)**.|
2650| NOTIFY_MOVE_SELF  | 4    | File moved (for example, the target file or folder is renamed or moved).<br>See example 1 **registerObserver**.    |
2651| NOTIFY_DEVICE_ONLINE<sup>11+</sup>   | 5    | Device goes online.    |
2652| NOTIFY_DEVICE_OFFLINE<sup>11+</sup>   | 6    | Device goes offline.    |
2653
2654## NotifyMessage<sup>10+</sup>
2655
2656Represents the notification message.
2657
2658**Model restriction**: This API can be used only in the stage model.
2659
2660**System capability**: SystemCapability.FileManagement.UserFileService
2661
2662**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2663
2664| Name| Type                       | Read-Only| Writable| Description                                                     |
2665| ---- | --------------------------- | ---- | ---- | --------------------------------------------------------- |
2666| type | [NotifyType](#notifytype10) | Yes  | No  | Notification type.                                           |
2667| 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.|
2668
2669## MoveResult<sup>11+</sup>
2670
2671Represents the information returned when the move operation fails. If the operation is successful, no information is returned.
2672
2673**Model restriction**: This API can be used only in the stage model.
2674
2675**System capability**: SystemCapability.FileManagement.UserFileService
2676
2677**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
2678
2679| Name     | Type  | Read-Only| Writable| Description                                                        |
2680| --------- | ------ | ---- | ---- | ------------------------------------------------------------ |
2681| sourceUri | string | Yes  | No  | URI of the source file or folder.                                              |
2682| destUri   | string | Yes  | No  | URI of the conflicting file. If the error is not caused by a file conflict, **destUri** is empty.    |
2683| errCode   | number | Yes  | No  | Error code. For details about the error codes, see [File Management Error Codes](errorcode-filemanagement.md).|
2684| errMsg    | string | Yes  | No  | Error message.                                                  |
2685