• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.file.fileAccess (User File Access and Management)
2
3The **fileAccess** module provides a framework for accessing and operating user files based on the ExtensionAbility mechanism. This module interacts with file management services, such as the media library and external storage management service, and provides a set of unified interfaces for system applications to access and manage files. The media library service allows access to user files on local and distributed devices. The external storage management service allows access to the user files stored on devices, such as shared disks, USB flash drives, and SD cards.
4
5>**NOTE**
6>
7> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8> - The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by **FilePicker** and **FileManager**.
9
10## Modules to Import
11
12```js
13import fileAccess from '@ohos.file.fileAccess';
14```
15
16## fileAccess.getFileAccessAbilityInfo
17
18getFileAccessAbilityInfo() : Promise<Array<Want>>
19
20Obtains information about all Wants with **extension** set to **fileAccess** in the system. A Want contains information for starting an ability. This API uses a promise to return the result.
21
22**Model restriction**: This API can be used only in the stage model.
23
24**System capability**: SystemCapability.FileManagement.UserFileService
25
26**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
27
28**Return value**
29
30  | Type| Description|
31  | --- | -- |
32  | Promise<Array<[Want](js-apis-app-ability-want.md)>> | Promise used to return the Want information obtained.|
33
34**Error codes**
35
36For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
37
38**Example**
39
40  ```js
41  async getFileAccessAbilityInfo() {
42    let wantInfos = [];
43    try {
44      wantInfos = await fileAccess.getFileAccessAbilityInfo();
45      console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos));
46    } catch (error) {
47      console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message);
48    }
49  }
50  ```
51
52## fileAccess.getFileAccessAbilityInfo
53
54getFileAccessAbilityInfo(callback: AsyncCallback<Array<Want>>): void
55
56Obtains 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.
57
58**Model restriction**: This API can be used only in the stage model.
59
60**System capability**: SystemCapability.FileManagement.UserFileService
61
62**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
63
64**Parameters**
65
66  | Name| Type| Mandatory| Description|
67  | --- | --- | --- | -- |
68  | callback | AsyncCallback<Array<[Want](js-apis-app-ability-want.md)>> | Yes| Promise used to return the Want information obtained.|
69
70**Error codes**
71
72For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
73
74**Example**
75
76  ```js
77  async getFileAccessAbilityInfo() {
78    try {
79      fileAccess.getFileAccessAbilityInfo(function (err, wantInfos) {
80        if (err) {
81          console.error("Failed to getFileAccessAbilityInfo in async, errCode:" + err.code + ", errMessage:" + err.message);
82          return;
83        }
84        console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos));
85      });
86    } catch (error) {
87      console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message);
88    }
89  }
90  ```
91
92## fileAccess.createFileAccessHelper
93
94createFileAccessHelper(context: Context, wants: Array<Want>) : FileAccessHelper
95
96Synchronously creates a **Helper** object to connect to the specified wants. The **Helper** object provides file access and management capabilities.
97
98**Model restriction**: This API can be used only in the stage model.
99
100**System capability**: SystemCapability.FileManagement.UserFileService
101
102**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
103
104**Parameters**
105
106  | Name| Type| Mandatory| Description|
107  | --- | --- | --- | -- |
108  | context | [Context](js-apis-inner-application-context.md) | Yes| Context of the ability.|
109  | wants | Array<[Want](js-apis-app-ability-want.md)> | Yes| Wants to connect.|
110
111**Return value**
112
113  | Type| Description|
114  | --- | -- |
115  | [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|
116
117**Error codes**
118
119For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
120
121**Example**
122
123  ```js
124  createFileAccessHelper() {
125    let fileAccessHelper = null;
126    / / Obtain wantInfos by using getFileAccessAbilityInfo().
127    // Create a helper object to interact with the media library service only.
128    let wantInfos = [
129      {
130        "bundleName": "com.ohos.medialibrary.medialibrarydata",
131        "abilityName": "FileExtensionAbility",
132      },
133    ]
134    try {
135      // this.context is passed by EntryAbility.
136      fileAccessHelper = fileAccess.createFileAccessHelper(this.context, wantInfos);
137      if (!fileAccessHelper)
138        console.error("createFileAccessHelper interface returns an undefined object");
139    } catch (error) {
140      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
141    }
142  }
143  ```
144
145## fileAccess.createFileAccessHelper
146
147createFileAccessHelper(context: Context) : FileAccessHelper
148
149Synchronously creates a **Helper** object to connect to all file management services in the system.
150
151**Model restriction**: This API can be used only in the stage model.
152
153**System capability**: SystemCapability.FileManagement.UserFileService
154
155**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
156
157**Parameters**
158
159  | Name| Type| Mandatory| Description|
160  | --- | --- | --- | -- |
161  | context | [Context](js-apis-inner-application-context.md) | Yes| Context of the ability.|
162
163**Return value**
164
165  | Type| Description|
166  | --- | -- |
167  | [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|
168
169**Error codes**
170
171For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
172
173**Example**
174
175  ```js
176  createFileAccessHelper() {
177    let fileAccessHelperAllServer = null;
178    // Create a Helper object to interact with all file management services configured with fileAccess in the system.
179    try {
180      // this.context is passed by EntryAbility.
181      fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context);
182      if (!fileAccessHelperAllServer)
183        console.error("createFileAccessHelper interface returns an undefined object");
184    } catch (error) {
185      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
186    }
187  }
188  ```
189
190## FileInfo
191
192Provides the file or directory attribute information and APIs.
193
194**Model restriction**: This API can be used only in the stage model.
195
196**System capability**: SystemCapability.FileManagement.UserFileService
197
198**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
199
200### Attributes
201
202| Name| Type  | Readable| Writable| Description    |
203| ------ | ------ | -------- | ------ | -------- |
204| uri | string | Yes| No| URI of the file or directory.|
205| fileName | string | Yes| No| Name of the file or directory.|
206| mode | number | Yes| No| Permissions on the file or directory.|
207| size | number | Yes| No|  Size of the file or directory.|
208| mtime | number | Yes| No|  Time when the file or directory was last modified.|
209| mimeType | string | Yes| No|  Multipurpose Internet Mail Extensions (MIME) type of the file or directory.|
210
211### listFile
212
213listFile(filter?: Filter) : FileIterator
214
215Synchronously obtains a **FileIterator** object that lists the next-level files (directories) matching the conditions of the filter from a directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, only built-in storage devices support the file filter.
216
217**Model restriction**: This API can be used only in the stage model.
218
219**System capability**: SystemCapability.FileManagement.UserFileService
220
221**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
222
223**Parameters**
224
225  | Name| Type| Mandatory| Description|
226  | --- | --- | -- | -- |
227  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
228
229**Return value**
230
231  | Type| Description|
232  | --- | -- |
233  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|
234
235**Error codes**
236
237For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
238
239**Example**
240
241  ```js
242  // fileInfoDir indicates information about a directory.
243  // let filter = { suffix : [".txt", ".jpg", ".xlsx"] };
244  let fileInfoDir = fileInfos[0];
245  let subfileInfos = [];
246  let isDone = false;
247  try {
248    let fileIterator = fileInfoDir.listFile();
249    // listFile() with the filter implementation.
250    // let fileIterator = rootInfo.listFile(filter);
251    if (!fileIterator) {
252      console.error("listFile interface returns an undefined object");
253      return;
254    }
255    while (!isDone) {
256      let result = fileIterator.next();
257      console.log("next result = " + JSON.stringify(result));
258      isDone = result.done;
259      if (!isDone)
260        subfileInfos.push(result.value);
261    }
262  } catch (error) {
263    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
264  }
265  ```
266
267### scanFile
268
269scanFile(filter?: Filter) : FileIterator
270
271Synchronously obtains a **FileIterator** object that recursively retrieves the files matching the conditions of the filter from a directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, this API supports only built-in storage devices.
272
273**Model restriction**: This API can be used only in the stage model.
274
275**System capability**: SystemCapability.FileManagement.UserFileService
276
277**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
278
279**Parameters**
280
281  | Name| Type| Mandatory| Description|
282  | --- | --- | -- | -- |
283  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
284
285**Return value**
286
287  | Type| Description|
288  | --- | -- |
289  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|
290
291**Error codes**
292
293For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
294
295**Example**
296
297  ```js
298  // fileInfoDir indicates information about a directory.
299  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
300  let fileInfoDir = fileInfos[0];
301  let subfileInfos = [];
302  let isDone = false;
303  try {
304    let fileIterator = fileInfoDir.scanFile();
305    // scanFile() with the filter implementation.
306    // let fileIterator = rootInfo.scanFile(filter);
307    if (!fileIterator) {
308      console.error("scanFile interface returns an undefined object");
309      return;
310    }
311    while (!isDone) {
312      let result = fileIterator.next();
313      console.log("next result = " + JSON.stringify(result));
314      isDone = result.done;
315      if (!isDone)
316        subfileInfos.push(result.value);
317    }
318  } catch (error) {
319    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
320  }
321  ```
322
323## FileIterator
324
325Provides the **FileIterator** object.
326
327**Model restriction**: This API can be used only in the stage model.
328
329**System capability**: SystemCapability.FileManagement.UserFileService
330
331**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
332
333### next
334
335next() : { value: FileInfo, done: boolean }
336
337Obtains information about the next-level files or directories.
338
339**Model restriction**: This API can be used only in the stage model.
340
341**System capability**: SystemCapability.FileManagement.UserFileService
342
343**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
344
345**Return value**
346
347| Type| Description|
348| --- | -- |
349| {value: [FileInfo](#fileinfo), done: boolean} | File or directory information obtained. This method traverses the specified directory until **true** is returned. The **value** field contains the file or directory information obtained.|
350
351**Error codes**
352
353For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
354
355## RootInfo
356
357Provides the device's root attribute information and APIs.
358
359**Model restriction**: This API can be used only in the stage model.
360
361**System capability**: SystemCapability.FileManagement.UserFileService
362
363**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
364
365### Attributes
366
367| Name| Type  | Readable| Writable| Description    |
368| ------ | ------ | -------- | ------ | -------- |
369| deviceType | number | Yes| No|Type of the device.|
370| uri | string | Yes| No| Root directory URI of the device.|
371| displayName | string | Yes| No| Device name.|
372| deviceFlags | number | Yes| No| Capabilities supported by the device.|
373
374### listFile
375
376listFile(filter?: Filter) : FileIterator
377
378Synchronously obtains a **FileIterator** object that lists the first-level files (directories) matching the conditions of the filter from the device root directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, only built-in storage devices support the file filter.
379
380**Model restriction**: This API can be used only in the stage model.
381
382**System capability**: SystemCapability.FileManagement.UserFileService
383
384**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
385
386**Parameters**
387
388  | Name| Type| Mandatory| Description|
389  | --- | --- | -- | -- |
390  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
391
392**Return value**
393
394  | Type| Description|
395  | --- | -- |
396  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|
397
398**Error codes**
399
400For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
401
402**Example**
403
404  ```js
405  // Obtain rootInfos by using getRoots().
406  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
407  let rootInfo = rootinfos[0];
408  let fileInfos = [];
409  let isDone = false;
410  try {
411    let fileIterator = rootInfo.listFile();
412    // listFile() with the filter implementation.
413    // let fileIterator = rootInfo.listFile(filter);
414    if (!fileIterator) {
415      console.error("listFile interface returns an undefined object");
416      return;
417    }
418    while (!isDone) {
419      let result = fileIterator.next();
420      console.log("next result = " + JSON.stringify(result));
421      isDone = result.done;
422      if (!isDone)
423        fileInfos.push(result.value);
424    }
425  } catch (error) {
426    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
427  }
428  ```
429
430### scanFile
431
432scanFile(filter?: Filter) : FileIterator
433
434Synchronously obtains a **FileIterator** object that recursively retrieves the files matching the conditions of the filter from the device root directory and returns [FileInfo](#fileinfo)using [next()](#next). Currently, this API supports only built-in storage devices.
435
436**Model restriction**: This API can be used only in the stage model.
437
438**System capability**: SystemCapability.FileManagement.UserFileService
439
440**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
441
442**Parameters**
443
444  | Name| Type| Mandatory| Description|
445  | --- | --- | -- | -- |
446  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
447
448**Return value**
449
450  | Type| Description|
451  | --- | -- |
452  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|
453
454**Error codes**
455
456For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
457
458**Example**
459
460  ```js
461  // Obtain rootInfos by using getRoots().
462  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
463  let rootInfo = rootInfos[0];
464  let fileInfos = [];
465  let isDone = false;
466  try {
467    let fileIterator = rootInfo.scanFile();
468    // scanFile with the filter implementation.
469    // let fileIterator = rootInfo.scanFile(filter);
470    if (!fileIterator) {
471      console.error("scanFile interface returns undefined object");
472      return;
473    }
474    while (!isDone) {
475      let result = fileIterator.next();
476      console.log("next result = " + JSON.stringify(result));
477      isDone = result.done;
478      if (!isDone)
479        fileInfos.push(result.value);
480    }
481  } catch (error) {
482    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
483  }
484  ```
485
486## RootIterator
487
488Provides an iterator object of the device root directory.
489
490**Model restriction**: This API can be used only in the stage model.
491
492**System capability**: SystemCapability.FileManagement.UserFileService
493
494**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
495
496### next
497
498next() : { value: RootInfo, done: boolean }
499
500Obtains the root directory of the next-level device.
501
502**Model restriction**: This API can be used only in the stage model.
503
504**System capability**: SystemCapability.FileManagement.UserFileService
505
506**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
507
508**Return value**
509
510| Type| Description|
511| --- | -- |
512| {value: [RootInfo](#rootinfo), done: boolean} | Root directory information obtained. This method traverses the directory until **true** is returned. The **value** field contains the root directory information.|
513
514**Error codes**
515
516For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
517
518## FileAccessHelper
519
520Provides a **FileAccessHelper** object.
521
522**Model restriction**: This API can be used only in the stage model.
523
524**System capability**: SystemCapability.FileManagement.UserFileService
525
526**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
527
528### getRoots
529
530getRoots() : Promise<RootIterator>
531
532Obtains information about the device root nodes of the file management service connected to the **Helper** object. This API uses a promise to return a **RootIterator** object,
533which returns [RootInfo](#rootinfo) by using [next](#next-1).
534
535**Model restriction**: This API can be used only in the stage model.
536
537**System capability**: SystemCapability.FileManagement.UserFileService
538
539**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
540
541**Return value**
542
543| Type| Description|
544| --- | -- |
545| Promise<[RootIterator](#rootiterator)> | Promise used to return the **RootIterator** object obtained.|
546
547**Error codes**
548
549For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
550
551**Example**
552
553  ```js
554  async getRoots() {
555    let rootIterator = null;
556    let rootinfos = [];
557    let isDone = false;
558    try {
559      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
560      rootIterator = await fileAccessHelper.getRoots();
561      if (!rootIterator) {
562        console.error("getRoots interface returns an undefined object");
563        return;
564      }
565      while (!isDone) {
566        let result = rootIterator.next();
567        console.log("next result = " + JSON.stringify(result));
568        isDone = result.done;
569        if (!isDone)
570          rootinfos.push(result.value);
571      }
572    } catch (error) {
573      console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
574    }
575  }
576  ```
577
578### getRoots
579
580getRoots(callback:AsyncCallback<RootIterator>) : void
581
582Obtains information about the device root nodes of the file management service connected to the **Helper** object. This API uses an asynchronous callback to return a **RootIterator** object,
583which returns [RootInfo](#rootinfo) by using [next](#next-1).
584
585**Model restriction**: This API can be used only in the stage model.
586
587**System capability**: SystemCapability.FileManagement.UserFileService
588
589**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
590
591**Parameters**
592
593| Name| Type| Mandatory| Description|
594| --- | --- | --- | -- |
595| callback | AsyncCallback<[RootIterator](#rootiterator)> | Yes| Callback invoked to return the **RootIterator** object obtained.|
596
597**Error codes**
598
599For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
600
601**Example**
602
603  ```js
604  async getRoots() {
605    let rootinfos = [];
606    let isDone = false;
607    try {
608      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
609      fileAccessHelper.getRoots(function (err, rootIterator) {
610        if (err) {
611          console.error("Failed to getRoots in async, errCode:" + err.code + ", errMessage:" + err.message);
612          return;
613        }
614        while (!isDone) {
615          let result = rootIterator.next();
616          console.log("next result = " + JSON.stringify(result));
617          isDone = result.done;
618          if (!isDone)
619            rootinfos.push(result.value);
620        }
621      });
622    } catch (error) {
623      console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
624    }
625  }
626  ```
627
628### createFile
629
630createFile(uri: string, displayName: string) : Promise<string>
631
632Creates a file in a directory. This API uses a promise to return the result.
633
634**Model restriction**: This API can be used only in the stage model.
635
636**System capability**: SystemCapability.FileManagement.UserFileService
637
638**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
639
640**Parameters**
641
642| Name| Type| Mandatory| Description|
643| --- | --- | --- | -- |
644| uri | string | Yes| URI of the destination directory for the file to create.|
645| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
646
647**Return value**
648
649| Type| Description|
650| --- | -- |
651| Promise<string> | Promise used to return the URI of the file created.|
652
653**Error codes**
654
655For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
656
657**Example**
658
659  ```js
660  // The media library URI is used as an example.
661  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
662  // You can use the URI obtained.
663  let sourceUri = "datashare:///media/file/6";
664  let displayName = "file1"
665  let fileUri = null;
666  try {
667    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
668    fileUri = await fileAccessHelper.createFile(sourceUri, displayName)
669    if (!fileUri) {
670      console.error("createFile return undefined object");
671      return;
672    }
673    console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri));
674  } catch (error) {
675    console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
676  };
677  ```
678
679### createFile
680
681createFile(uri: string, displayName: string, callback: AsyncCallback<string>) : void
682
683Creates a file in a directory. This API uses an asynchronous callback to return the result.
684
685**Model restriction**: This API can be used only in the stage model.
686
687**System capability**: SystemCapability.FileManagement.UserFileService
688
689**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
690
691**Parameters**
692
693| Name| Type| Mandatory| Description|
694| --- | --- | --- | -- |
695| uri | string | Yes| URI of the destination directory for the file to create.|
696| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
697| callback | AsyncCallback<string> | Yes| Callback invoked to return the URI of the file created.|
698
699**Error codes**
700
701For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
702
703**Example**
704
705  ```js
706  // The media library URI is used as an example.
707  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
708  // You can use the URI obtained.
709  let sourceUri = "datashare:///media/file/6";
710  let displayName = "file1"
711  try {
712    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
713    fileAccessHelper.createFile(sourceUri, displayName, function (err, fileUri) {
714      if (err) {
715        console.error("Failed to createFile in async, errCode:" + err.code + ", errMessage:" + err.message);
716        return;
717      }
718      console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri));
719    });
720  } catch (error) {
721    console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
722  };
723  ```
724
725### mkDir
726
727mkDir(parentUri: string, displayName: string) : Promise<string>
728
729Creates a directory. This API uses a promise to return the result.
730
731**Model restriction**: This API can be used only in the stage model.
732
733**System capability**: SystemCapability.FileManagement.UserFileService
734
735**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
736
737**Parameters**
738
739| Name| Type| Mandatory| Description|
740| --- | --- | --- | -- |
741| parentUri | string | Yes| URI of the destination directory for the directory to create.|
742| displayName | string | Yes| Name of the directory to create.|
743
744**Return value**
745
746| Type| Description|
747| --- | -- |
748| Promise<string> | Promise used to return the URI of the directory created.|
749
750**Error codes**
751
752For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
753
754**Example**
755
756  ```js
757  // The media library URI is used as an example.
758  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
759  // You can use the URI obtained.
760  let sourceUri = "datashare:///media/file/6";
761  let dirName = "dirTest"
762  let dirUri = null;
763  try {
764    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
765    dirUri = await fileAccessHelper.mkDir(sourceUri, dirName)
766    if (!dirUri) {
767      console.error("mkDir return undefined object");
768      return;
769    }
770    console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri));
771  } catch (error) {
772    console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message);
773  };
774  ```
775
776### mkDir
777
778mkDir(parentUri: string, displayName: string, callback: AsyncCallback<string>) : void
779
780Creates a directory. This API uses an asynchronous callback to return the result.
781
782**Model restriction**: This API can be used only in the stage model.
783
784**System capability**: SystemCapability.FileManagement.UserFileService
785
786**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
787
788**Parameters**
789
790| Name| Type| Mandatory| Description|
791| --- | --- | --- | -- |
792| parentUri | string | Yes| URI of the destination directory for the directory to create.|
793| displayName | string | Yes| Name of the directory to create.|
794| callback | AsyncCallback<string> | Yes| Callback invoked to return the URI of the directory created.|
795
796**Error codes**
797
798For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
799
800**Example**
801
802  ```js
803  // The media library URI is used as an example.
804  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
805  // You can use the URI obtained.
806  let sourceUri = "datashare:///media/file/6";
807  let dirName = "dirTest"
808  try {
809    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
810    fileAccessHelper.mkDir(sourceUri, dirName, function (err, dirUri) {
811      if (err) {
812        console.error("Failed to mkDir in async, errCode:" + err.code + ", errMessage:" + err.message);
813        return;
814      }
815      console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri));
816    });
817  } catch (error) {
818    console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message);
819  };
820  ```
821
822### openFile
823
824openFile(uri: string, flags: OPENFLAGS) : Promise<number>
825
826Opens a file. This API uses a promise to return the result.
827
828**Model restriction**: This API can be used only in the stage model.
829
830**System capability**: SystemCapability.FileManagement.UserFileService
831
832**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
833
834**Parameters**
835
836| Name| Type| Mandatory| Description|
837| --- | --- | --- | -- |
838| uri | string | Yes| URI of the file to open.|
839| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
840
841**Return value**
842
843| Type| Description|
844| --- | -- |
845| Promise<number> | Promise used to return the file descriptor (FD) of the file opened.|
846
847**Error codes**
848
849For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
850
851**Example**
852
853  ```js
854  // The media library URI is used as an example.
855  //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
856  // You can use the URI obtained.
857  let targetUri  = "datashare:///media/file/100";
858  try {
859    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
860    let fd = await fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ);
861  } catch (error) {
862    console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message);
863  };
864  ```
865
866### openFile
867
868openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback<number>) : void
869
870Opens a file. This API uses an asynchronous callback to return the result.
871
872**Model restriction**: This API can be used only in the stage model.
873
874**System capability**: SystemCapability.FileManagement.UserFileService
875
876**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
877
878**Parameters**
879
880| Name| Type| Mandatory| Description|
881| --- | --- | --- | -- |
882| uri | string | Yes| URI of the file to open.|
883| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
884| callback | AsyncCallback<number> | Yes| Callback invoked to return the FD of the file opened.|
885
886**Error codes**
887
888For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
889
890**Example**
891
892  ```js
893  // The media library URI is used as an example.
894  //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
895  // You can use the URI obtained.
896  let targetUri  = "datashare:///media/file/100";
897  try {
898    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
899    fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ, function (err, fd) {
900      if (err) {
901        console.error("Failed to openFile in async, errCode:" + err.code + ", errMessage:" + err.message);
902        return;
903      }
904      console.log("openFile sucess, fd: " + fd);
905    });
906  } catch (error) {
907    console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message);
908  };
909  ```
910
911### delete
912
913delete(uri: string) : Promise<number>
914
915Deletes a file or directory. This API uses a promise to return the result.
916
917**Model restriction**: This API can be used only in the stage model.
918
919**System capability**: SystemCapability.FileManagement.UserFileService
920
921**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
922
923**Parameters**
924
925| Name| Type| Mandatory| Description|
926| --- | --- | --- | -- |
927| uri | string | Yes| URI of the file or directory to delete.|
928
929**Return value**
930
931| Type| Description|
932| --- | -- |
933| Promise<number&gt | Promise used to return the result.|
934
935**Error codes**
936
937For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
938
939**Example**
940
941  ```js
942  // The media library URI is used as an example.
943  //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
944  // You can use the URI obtained.
945  let targetUri = "datashare:///media/file/100";
946  try {
947    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
948    let code = await fileAccessHelper.delete(targetUri);
949    if (code != 0)
950      console.error("delete failed, code " + code);
951  } catch (error) {
952    console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message);
953  };
954  ```
955
956### delete
957
958delete(uri: string, callback: AsyncCallback<number>) : void
959
960Deletes a file or directory. This API uses an asynchronous callback to return the result.
961
962**Model restriction**: This API can be used only in the stage model.
963
964**System capability**: SystemCapability.FileManagement.UserFileService
965
966**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
967
968**Parameters**
969
970| Name| Type| Mandatory| Description|
971| --- | --- | --- | -- |
972| uri | string | Yes| URI of the file or directory to delete.|
973| callback | AsyncCallback<number> | Yes| Callback invoked to return the result.|
974
975**Error codes**
976
977For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
978
979**Example**
980
981  ```js
982  // The media library URI is used as an example.
983  //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
984  // You can use the URI obtained.
985  let targetUri = "datashare:///media/file/100";
986  try {
987    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
988    fileAccessHelper.delete(targetUri, function (err, code) {
989      if (err) {
990        console.error("Failed to delete in async, errCode:" + err.code + ", errMessage:" + err.message);
991        return;
992      }
993      console.log("delete sucess, code: " + code);
994    });
995  } catch (error) {
996    console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message);
997  };
998  ```
999
1000### move
1001
1002move(sourceFile: string, destFile: string) : Promise<string>
1003
1004Moves a file or directory. This API uses a promise to return the result. Currently, this API does not support move of files or directories across devices.
1005
1006**Model restriction**: This API can be used only in the stage model.
1007
1008**System capability**: SystemCapability.FileManagement.UserFileService
1009
1010**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1011
1012**Parameters**
1013
1014| Name| Type| Mandatory| Description|
1015| --- | --- | --- | -- |
1016| sourceFile | string | Yes| URI of the file or directory to move.|
1017| destFile | string | Yes| URI of the destination directory, to which the file or directory will be moved.|
1018
1019**Return value**
1020
1021| Type| Description|
1022| ----- | ------ |
1023| Promise<string> | Promise used to return the URI of the file or directory in the destination directory.|
1024
1025**Error codes**
1026
1027For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1028
1029**Example**
1030
1031  ```js
1032  // The media library URI is used as an example.
1033  //In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
1034  // You can use the URI obtained.
1035  let sourceFile = "datashare:///media/file/102";
1036  let destFile = "datashare:///media/file/101";
1037  try {
1038    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1039    let fileUri = await fileAccessHelper.move(sourceFile, destFile);
1040    console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
1041  } catch (error) {
1042    console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
1043  };
1044  ```
1045
1046### move
1047
1048move(sourceFile: string, destFile: string, callback: AsyncCallback<string>) : void
1049
1050Moves a file or directory. This API uses an asynchronous callback to return the result. Currently, this API does not support move of files or directories across devices.
1051
1052**Model restriction**: This API can be used only in the stage model.
1053
1054**System capability**: SystemCapability.FileManagement.UserFileService
1055
1056**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1057
1058**Parameters**
1059
1060| Name| Type| Mandatory| Description|
1061| --- | --- | --- | -- |
1062| sourceFile | string | Yes| URI of the file or directory to move.|
1063| destFile | string | Yes| URI of the destination directory, to which the file or directory will be moved.|
1064| callback | AsyncCallback<string> | Yes| Callback invoked to return the URI of the file or directory in the destination directory.|
1065
1066**Error codes**
1067
1068For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1069
1070**Example**
1071
1072  ```js
1073  // The media library URI is used as an example.
1074  //In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
1075  // You can use the URI obtained.
1076  let sourceFile = "datashare:///media/file/102";
1077  let destFile = "datashare:///media/file/101";
1078  try {
1079    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1080    fileAccessHelper.move(sourceFile, destFile, function (err, fileUri) {
1081      if (err) {
1082        console.error("Failed to move in async, errCode:" + err.code + ", errMessage:" + err.message);
1083        return;
1084      }
1085      console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
1086    });
1087  } catch (error) {
1088    console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
1089  };
1090  ```
1091
1092### rename
1093
1094rename(uri: string, displayName: string) : Promise<string>
1095
1096Renames a file or directory. This API uses a promise to return the result.
1097
1098**Model restriction**: This API can be used only in the stage model.
1099
1100**System capability**: SystemCapability.FileManagement.UserFileService
1101
1102**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1103
1104**Parameters**
1105
1106| Name| Type| Mandatory| Description|
1107| --- | --- | --- | -- |
1108| uri | string | Yes| URI of the file or directory to rename.|
1109| displayName | string | Yes| New name of the file or directory, which can contain the file name extension.|
1110
1111**Return value**
1112
1113| Type| Description|
1114| --- | -- |
1115| Promise<string> | Promise used to return the URI of the renamed file or directory.|
1116
1117**Error codes**
1118
1119For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1120
1121**Example**
1122
1123  ```js
1124  // The media library URI is used as an example.
1125  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
1126  // You can use the URI obtained.
1127  let sourceDir = "datashare:///media/file/100";
1128  try {
1129    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1130    let DestDir = await fileAccessHelper.rename(sourceDir, "testDir");
1131    console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
1132  } catch (error) {
1133    console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message);
1134  };
1135  ```
1136
1137### rename
1138
1139rename(uri: string, displayName: string, callback: AsyncCallback<string>) : void
1140
1141Renames a file or directory. This API uses an asynchronous callback to return the result.
1142
1143**Model restriction**: This API can be used only in the stage model.
1144
1145**System capability**: SystemCapability.FileManagement.UserFileService
1146
1147**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1148
1149**Parameters**
1150
1151| Name| Type| Mandatory| Description|
1152| --- | --- | --- | -- |
1153| uri | string | Yes| URI of the file or directory to rename.|
1154| displayName | string | Yes| New name of the file or directory, which can contain the file name extension.|
1155| callback | AsyncCallback<string> | Yes| Callback invoked to return the URI of the renamed file or directory.|
1156
1157**Error codes**
1158
1159For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1160
1161**Example**
1162
1163  ```js
1164  // The media library URI is used as an example.
1165  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
1166  // You can use the URI obtained.
1167  let sourceDir = "datashare:///media/file/100";
1168  try {
1169    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1170    fileAccessHelper.rename(sourceDir, "testDir", function (err, DestDir) {
1171      if (err) {
1172        console.error("Failed to rename in async, errCode:" + err.code + ", errMessage:" + err.message);
1173        return;
1174      }
1175      console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
1176    });
1177  } catch (error) {
1178    console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message);
1179  };
1180  ```
1181
1182### access
1183
1184access(sourceFileUri: string) : Promise<boolean>
1185
1186Checks whether a file or directory exists. This API uses a promise to return the result.
1187
1188**Model restriction**: This API can be used only in the stage model.
1189
1190**System capability**: SystemCapability.FileManagement.UserFileService
1191
1192**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1193
1194**Parameters**
1195
1196| Name| Type| Mandatory| Description|
1197| --- | --- | --- | -- |
1198| sourceFileUri | string | Yes| URI of the file or directory.|
1199
1200**Return value**
1201
1202| Type| Description|
1203| --- | -- |
1204| Promise<boolean> | Promise used to return the result.|
1205
1206**Error codes**
1207
1208For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1209
1210**Example**
1211
1212  ```js
1213  // The media library URI is used as an example.
1214  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
1215  // You can use the URI obtained.
1216  let sourceDir = "datashare:///media/file/100";
1217  try {
1218    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1219    let existJudgment = await fileAccessHelper.access(sourceDir);
1220    if (existJudgment)
1221      console.log("sourceDir exists");
1222    else
1223      console.log("sourceDir does not exist");
1224  } catch (error) {
1225    console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message);
1226  };
1227  ```
1228
1229### access
1230
1231access(sourceFileUri: string, callback: AsyncCallback<boolean>) : void
1232
1233Checks whether a file or directory exists. This API uses an asynchronous callback to return the result.
1234
1235**Model restriction**: This API can be used only in the stage model.
1236
1237**System capability**: SystemCapability.FileManagement.UserFileService
1238
1239**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
1240
1241**Parameters**
1242
1243| Name| Type| Mandatory| Description|
1244| --- | --- | --- | -- |
1245| sourceFileUri | string | Yes| URI of the file or directory.|
1246| callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result.|
1247
1248**Error codes**
1249
1250For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
1251
1252**Example**
1253
1254  ```js
1255  // The media library URI 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 = "datashare:///media/file/100";
1259  try {
1260    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
1261    fileAccessHelper.access(sourceDir, function (err, existJudgment) {
1262      if (err) {
1263        console.error("Failed to access in async, errCode:" + err.code + ", errMessage:" + err.message);
1264        return;
1265      }
1266      if (existJudgment)
1267        console.log("sourceDir exists");
1268      else
1269        console.log("sourceDir does not exist");
1270    });
1271  } catch (error) {
1272    console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message);
1273  };
1274  ```
1275
1276## OPENFLAGS
1277
1278Enumerates the modes for opening a file.
1279
1280**System capability**: SystemCapability.FileManagement.UserFileService
1281
1282| Name| Value| Description|
1283| ----- | ------ | ------ |
1284| READ | 0o0 | Read mode.|
1285| WRITE | 0o1 | Write mode.|
1286| WRITE_READ | 0o2 | Read/Write mode.|
1287