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