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