js-apis-fileAccess.md 65.4 KB
Newer Older
A
Annie_wang 已提交
1
# @ohos.file.fileAccess (User File Access and Management)
A
Annie_wang 已提交
2

A
Annie_wang 已提交
3
The **fileAccess** module provides a framework for accessing and operating user files based on the ExtensionAbility mechanism. This module interacts with file management services, such as the media library and external storage management service, and provides a set of unified interfaces for system applications to access and manage files. The media library service allows access to user files on local and distributed devices. The external storage management service allows access to the user files stored on devices, such as shared disks, USB flash drives, and SD cards.
A
Annie_wang 已提交
4 5 6

>**NOTE**
>
A
Annie_wang 已提交
7 8
> - 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.
> - 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**.
A
Annie_wang 已提交
9 10 11 12

## Modules to Import

```js
A
Annie_wang 已提交
13
import fileAccess from '@ohos.file.fileAccess';
A
Annie_wang 已提交
14 15 16 17
```

## fileAccess.getFileAccessAbilityInfo

A
Annie_wang 已提交
18
getFileAccessAbilityInfo() : Promise<Array<Want>>
A
Annie_wang 已提交
19

A
Annie_wang 已提交
20 21 22
Obtains 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.

**Model restriction**: This API can be used only in the stage model.
A
Annie_wang 已提交
23 24 25

**System capability**: SystemCapability.FileManagement.UserFileService

A
Annie_wang 已提交
26
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
A
Annie_wang 已提交
27 28 29

**Return value**

A
Annie_wang 已提交
30 31 32 33 34 35 36
  | Type| Description|
  | --- | -- |
  | Promise<Array<[Want](js-apis-app-ability-want.md)>> | Promise used to return the Want information obtained.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
37 38 39 40 41 42 43 44 45 46

**Example**

  ```js
  async getFileAccessAbilityInfo() {
    let wantInfos = [];
    try {
      wantInfos = await fileAccess.getFileAccessAbilityInfo();
      console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos));
    } catch (error) {
A
Annie_wang 已提交
47 48 49 50 51 52 53
      console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message);
    }
  }
  ```

## fileAccess.getFileAccessAbilityInfo

A
Annie_wang 已提交
54 55 56
getFileAccessAbilityInfo(callback: AsyncCallback<Array<Want>>): void

Obtains 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.
A
Annie_wang 已提交
57

A
Annie_wang 已提交
58
**Model restriction**: This API can be used only in the stage model.
A
Annie_wang 已提交
59 60 61 62 63 64 65

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED

**Parameters**

A
Annie_wang 已提交
66 67 68 69 70 71 72
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | callback | AsyncCallback<Array<[Want](js-apis-app-ability-want.md)>> | Yes| Promise used to return the Want information obtained.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

**Example**

  ```js
  async getFileAccessAbilityInfo() {
    try {
      fileAccess.getFileAccessAbilityInfo(function (err, wantInfos) {
        if (err) {
          console.error("Failed to getFileAccessAbilityInfo in async, errCode:" + err.code + ", errMessage:" + err.message);
          return;
        }
        console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos));
      });
    } catch (error) {
      console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
88 89 90 91 92 93 94 95
    }
  }
  ```

## fileAccess.createFileAccessHelper

createFileAccessHelper(context: Context, wants: Array<Want>) : FileAccessHelper

A
Annie_wang 已提交
96 97 98
Synchronously creates a **Helper** object to connect to the specified Wants. The **Helper** object provides file access and management capabilities.

**Model restriction**: This API can be used only in the stage model.
A
Annie_wang 已提交
99 100 101

**System capability**: SystemCapability.FileManagement.UserFileService

A
Annie_wang 已提交
102
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
A
Annie_wang 已提交
103 104 105

**Parameters**

A
Annie_wang 已提交
106 107 108 109
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | context | [Context](js-apis-inner-application-context.md) | Yes| Context of the ability.|
  | wants | Array<[Want](js-apis-app-ability-want.md)> | Yes| Wants to connect.|
A
Annie_wang 已提交
110 111 112

**Return value**

A
Annie_wang 已提交
113 114 115 116 117 118 119
  | Type| Description|
  | --- | -- |
  | [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
120 121 122 123 124

**Example**

  ```js
  createFileAccessHelper() {
A
Annie_wang 已提交
125
    let fileAccessHelper = null;
A
Annie_wang 已提交
126
    // Obtain wantInfos by using getFileAccessAbilityInfo().
A
Annie_wang 已提交
127
    // Create a helper object to interact with the media library service only.
A
Annie_wang 已提交
128 129 130 131 132 133 134
    let wantInfos = [
      {
        "bundleName": "com.ohos.medialibrary.medialibrarydata",
        "abilityName": "FileExtensionAbility",
      },
    ]
    try {
A
Annie_wang 已提交
135
      // this.context is passed by EntryAbility.
A
Annie_wang 已提交
136 137
      fileAccessHelper = fileAccess.createFileAccessHelper(this.context, wantInfos);
      if (!fileAccessHelper)
A
Annie_wang 已提交
138 139
        console.error("createFileAccessHelper interface returns an undefined object");
    } catch (error) {
A
Annie_wang 已提交
140
      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
141 142 143 144 145 146 147 148
    }
  }
  ```

## fileAccess.createFileAccessHelper

createFileAccessHelper(context: Context) : FileAccessHelper

A
Annie_wang 已提交
149
Synchronously creates a **Helper** object to connect to all file management services in the system.
A
Annie_wang 已提交
150

A
Annie_wang 已提交
151 152
**Model restriction**: This API can be used only in the stage model.

A
Annie_wang 已提交
153 154
**System capability**: SystemCapability.FileManagement.UserFileService

A
Annie_wang 已提交
155
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
A
Annie_wang 已提交
156 157 158

**Parameters**

A
Annie_wang 已提交
159 160 161
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | context | [Context](js-apis-inner-application-context.md) | Yes| Context of the ability.|
A
Annie_wang 已提交
162 163 164

**Return value**

A
Annie_wang 已提交
165 166 167 168 169 170 171
  | Type| Description|
  | --- | -- |
  | [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
172 173 174 175 176

**Example**

  ```js
  createFileAccessHelper() {
A
Annie_wang 已提交
177
    let fileAccessHelperAllServer = null;
A
Annie_wang 已提交
178 179
    // Create a Helper object to interact with all file management services configured with fileAccess in the system.
    try {
A
Annie_wang 已提交
180
      // this.context is passed by EntryAbility.
A
Annie_wang 已提交
181 182
      fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context);
      if (!fileAccessHelperAllServer)
A
Annie_wang 已提交
183 184
        console.error("createFileAccessHelper interface returns an undefined object");
    } catch (error) {
A
Annie_wang 已提交
185
      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
186 187 188 189
    }
  }
  ```

A
Annie_wang 已提交
190 191 192 193 194 195 196 197 198
## FileInfo

Provides the file or directory attribute information and APIs.

**Model restriction**: This API can be used only in the stage model.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
A
Annie_wang 已提交
199

A
Annie_wang 已提交
200
### Attributes
A
Annie_wang 已提交
201

A
Annie_wang 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
| Name| Type  | Readable| Writable| Description    |
| ------ | ------ | -------- | ------ | -------- |
| uri | string | Yes| No| URI of the file or directory.|
| relativePath<sup>10+</sup> | string | Yes| No| Relative path of the file or directory.|
| fileName | string | Yes| No| Name of the file or directory.|
| mode | number | Yes| No| Permissions on the file or directory.|
| size | number | Yes| No|  Size of the file or directory.|
| mtime | number | Yes| No|  Time when the file or directory was last modified.|
| mimeType | string | Yes| No|  Multipurpose Internet Mail Extensions (MIME) type of the file or directory.|

### listFile

listFile(filter?: Filter) : FileIterator

Synchronously obtains a **FileIterator** object that lists the next-level files (directories) matching the conditions of the filter from a directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, only built-in storage devices support the file filter.

**Model restriction**: This API can be used only in the stage model.
A
Annie_wang 已提交
219 220 221 222 223

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

A
Annie_wang 已提交
224 225 226 227 228 229
**Parameters**

  | Name| Type| Mandatory| Description|
  | --- | --- | -- | -- |
  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |

A
Annie_wang 已提交
230 231
**Return value**

A
Annie_wang 已提交
232 233 234 235 236 237 238
  | Type| Description|
  | --- | -- |
  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
239 240 241 242

**Example**

  ```js
A
Annie_wang 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  // fileInfoDir indicates information about a directory.
  // let filter = { suffix : [".txt", ".jpg", ".xlsx"] };
  let fileInfoDir = fileInfos[0];
  let subfileInfos = [];
  let isDone = false;
  try {
    let fileIterator = fileInfoDir.listFile();
    // listFile() with the filter implementation.
    // let fileIterator = rootInfo.listFile(filter);
    if (!fileIterator) {
      console.error("listFile interface returns an undefined object");
      return;
    }
    while (!isDone) {
      let result = fileIterator.next();
      console.log("next result = " + JSON.stringify(result));
      isDone = result.done;
      if (!isDone)
        subfileInfos.push(result.value);
A
Annie_wang 已提交
262
    }
A
Annie_wang 已提交
263 264
  } catch (error) {
    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
265 266 267
  }
  ```

A
Annie_wang 已提交
268 269 270
### scanFile

scanFile(filter?: Filter) : FileIterator;
A
Annie_wang 已提交
271

A
Annie_wang 已提交
272
Synchronously obtains a **FileIterator** object that recursively retrieves the files matching the conditions of the filter from a directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, this API supports only built-in storage devices.
A
Annie_wang 已提交
273

A
Annie_wang 已提交
274
**Model restriction**: This API can be used only in the stage model.
A
Annie_wang 已提交
275 276 277 278 279 280 281

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294
  | Name| Type| Mandatory| Description|
  | --- | --- | -- | -- |
  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |

**Return value**

  | Type| Description|
  | --- | -- |
  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
295 296 297 298

**Example**

  ```js
A
Annie_wang 已提交
299 300 301 302 303 304 305 306 307 308 309 310
  // fileInfoDir indicates information about a directory.
  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
  let fileInfoDir = fileInfos[0];
  let subfileInfos = [];
  let isDone = false;
  try {
    let fileIterator = fileInfoDir.scanFile();
    // scanFile() with the filter implementation.
    // let fileIterator = rootInfo.scanFile(filter);
    if (!fileIterator) {
      console.error("scanFile interface returns an undefined object");
      return;
A
Annie_wang 已提交
311
    }
A
Annie_wang 已提交
312 313 314 315 316 317 318 319 320
    while (!isDone) {
      let result = fileIterator.next();
      console.log("next result = " + JSON.stringify(result));
      isDone = result.done;
      if (!isDone)
        subfileInfos.push(result.value);
    }
  } catch (error) {
    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
321 322 323
  }
  ```

A
Annie_wang 已提交
324
## FileIterator
A
Annie_wang 已提交
325

A
Annie_wang 已提交
326
Provides the **FileIterator** object.
A
Annie_wang 已提交
327

A
Annie_wang 已提交
328
**Model restriction**: This API can be used only in the stage model.
A
Annie_wang 已提交
329 330 331 332 333

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

A
Annie_wang 已提交
334
### next
A
Annie_wang 已提交
335

A
Annie_wang 已提交
336 337 338 339 340 341 342
next() : { value: FileInfo, done: boolean }

Obtains information about the next-level files or directories.

**Model restriction**: This API can be used only in the stage model.

**System capability**: SystemCapability.FileManagement.UserFileService
A
Annie_wang 已提交
343

A
Annie_wang 已提交
344
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
A
Annie_wang 已提交
345 346 347

**Return value**

A
Annie_wang 已提交
348 349
| Type| Description|
| --- | -- |
A
Annie_wang 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
| {value: [FileInfo](#fileinfo), done: boolean} | File or directory information obtained. This method traverses the specified directory until **true** is returned. The **value** field contains the file or directory information obtained.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).

## RootInfo

Provides the device's root attribute information and APIs.

**Model restriction**: This API can be used only in the stage model.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

### Attributes

| Name| Type  | Readable| Writable| Description    |
| ------ | ------ | -------- | ------ | -------- |
| deviceType | number | Yes| No|Type of the device.|
| uri | string | Yes| No| Root directory URI of the device.|
| relativePath<sup>10+</sup> | string | Yes| No| Relative path of the root directory.|
| displayName | string | Yes| No| Device name.|
| deviceFlags | number | Yes| No| Capabilities supported by the device.|

### listFile

listFile(filter?: Filter) : FileIterator

Synchronously obtains a **FileIterator** object that lists the first-level files (directories) matching the conditions of the filter from the device root directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, only built-in storage devices support the file filter.

**Model restriction**: This API can be used only in the stage model.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

  | Name| Type| Mandatory| Description|
  | --- | --- | -- | -- |
  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |

**Return value**

  | Type| Description|
  | --- | -- |
  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
403 404 405 406

**Example**

  ```js
A
Annie_wang 已提交
407
  // Obtain rootInfos by using getRoots().
A
Annie_wang 已提交
408 409 410 411 412 413
  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
  let rootInfo = rootinfos[0];
  let fileInfos = [];
  let isDone = false;
  try {
    let fileIterator = rootInfo.listFile();
A
Annie_wang 已提交
414
    // listFile() with the filter implementation.
A
Annie_wang 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427
    // let fileIterator = rootInfo.listFile(filter);
    if (!fileIterator) {
      console.error("listFile interface returns an undefined object");
      return;
    }
    while (!isDone) {
      let result = fileIterator.next();
      console.log("next result = " + JSON.stringify(result));
      isDone = result.done;
      if (!isDone)
        fileInfos.push(result.value);
    }
  } catch (error) {
A
Annie_wang 已提交
428
    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
429 430 431
  }
  ```

A
Annie_wang 已提交
432
### scanFile
A
Annie_wang 已提交
433 434 435

scanFile(filter?: Filter) : FileIterator

A
Annie_wang 已提交
436 437 438
Synchronously obtains a **FileIterator** object that recursively retrieves the files matching the conditions of the filter from the device root directory and returns [FileInfo](#fileinfo)using [next()](#next). Currently, this API supports only built-in storage devices.

**Model restriction**: This API can be used only in the stage model.
A
Annie_wang 已提交
439 440 441 442 443 444 445

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
446 447 448
  | Name| Type| Mandatory| Description|
  | --- | --- | -- | -- |
  | filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
A
Annie_wang 已提交
449 450 451

**Return value**

A
Annie_wang 已提交
452 453 454 455 456 457 458
  | Type| Description|
  | --- | -- |
  | [FileIterator](#fileiterator) | **FileIterator** object obtained.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
459 460 461 462

**Example**

  ```js
A
Annie_wang 已提交
463
  // Obtain rootInfos by using getRoots().
A
Annie_wang 已提交
464
  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
A
Annie_wang 已提交
465
  let rootInfo = rootInfos[0];
A
Annie_wang 已提交
466 467 468
  let fileInfos = [];
  let isDone = false;
  try {
A
Annie_wang 已提交
469
    let fileIterator = rootInfo.scanFile();
A
Annie_wang 已提交
470
    // scanFile with the filter implementation.
A
Annie_wang 已提交
471 472 473 474 475 476 477 478 479 480 481 482
    // let fileIterator = rootInfo.scanFile(filter);
    if (!fileIterator) {
      console.error("scanFile interface returns undefined object");
      return;
    }
    while (!isDone) {
      let result = fileIterator.next();
      console.log("next result = " + JSON.stringify(result));
      isDone = result.done;
      if (!isDone)
        fileInfos.push(result.value);
    }
A
Annie_wang 已提交
483
  } catch (error) {
A
Annie_wang 已提交
484
    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
485 486 487
  }
  ```

A
Annie_wang 已提交
488
## RootIterator
A
Annie_wang 已提交
489

A
Annie_wang 已提交
490
Provides an iterator object of the device root directory.
A
Annie_wang 已提交
491

A
Annie_wang 已提交
492
**Model restriction**: This API can be used only in the stage model.
A
Annie_wang 已提交
493 494 495 496 497

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

A
Annie_wang 已提交
498
### next
A
Annie_wang 已提交
499

A
Annie_wang 已提交
500 501 502 503 504 505 506 507 508
next() : { value: RootInfo, done: boolean }

Obtains the root directory of the next-level device.

**Model restriction**: This API can be used only in the stage model.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
A
Annie_wang 已提交
509 510 511

**Return value**

A
Annie_wang 已提交
512 513
| Type| Description|
| --- | -- |
A
Annie_wang 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
| {value: [RootInfo](#rootinfo), done: boolean} | Root directory information obtained. This method traverses the directory until **true** is returned. The **value** field contains the root directory information.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).

## FileAccessHelper

Provides a **FileAccessHelper** object.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

### getRoots

getRoots() : Promise&lt;RootIterator&gt;

Obtains information about the device root nodes of the file management service connected to the **Helper** object. This API uses a promise to return a **RootIterator** object,
which returns [RootInfo](#rootinfo) by using [next](#next-1).

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Return value**

| Type| Description|
| --- | -- |
| Promise&lt;[RootIterator](#rootiterator)&gt; | Promise used to return the **RootIterator** object obtained.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
548 549 550 551

**Example**

  ```js
A
Annie_wang 已提交
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
  async getRoots() {
    let rootIterator = null;
    let rootinfos = [];
    let isDone = false;
    try {
      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
      rootIterator = await fileAccessHelper.getRoots();
      if (!rootIterator) {
        console.error("getRoots interface returns an undefined object");
        return;
      }
      while (!isDone) {
        let result = rootIterator.next();
        console.log("next result = " + JSON.stringify(result));
        isDone = result.done;
        if (!isDone)
          rootinfos.push(result.value);
      }
    } catch (error) {
      console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
572 573 574 575
    }
  }
  ```

A
Annie_wang 已提交
576
### getRoots
A
Annie_wang 已提交
577

A
Annie_wang 已提交
578
getRoots(callback:AsyncCallback&lt;RootIterator&gt;) : void
A
Annie_wang 已提交
579

A
Annie_wang 已提交
580 581
Obtains information about the device root nodes of the file management service connected to the **Helper** object. This API uses an asynchronous callback to return a **RootIterator** object,
which returns [RootInfo](#rootinfo) by using [next](#next-1).
A
Annie_wang 已提交
582 583 584 585 586 587 588

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
589
| Name| Type| Mandatory| Description|
A
Annie_wang 已提交
590 591
| --- | --- | --- | -- |
| callback | AsyncCallback&lt;[RootIterator](#rootiterator)&gt; | Yes| Callback invoked to return the **RootIterator** object obtained.|
A
Annie_wang 已提交
592

A
Annie_wang 已提交
593
**Error codes**
A
Annie_wang 已提交
594

A
Annie_wang 已提交
595
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
596 597 598 599

**Example**

  ```js
A
Annie_wang 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
  async getRoots() {
    let rootinfos = [];
    let isDone = false;
    try {
      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
      fileAccessHelper.getRoots(function (err, rootIterator) {
        if (err) {
          console.error("Failed to getRoots in async, errCode:" + err.code + ", errMessage:" + err.message);
          return;
        }
        while (!isDone) {
          let result = rootIterator.next();
          console.log("next result = " + JSON.stringify(result));
          isDone = result.done;
          if (!isDone)
            rootinfos.push(result.value);
        }
      });
    } catch (error) {
      console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
620 621 622 623
    }
  }
  ```

A
Annie_wang 已提交
624
### createFile
A
Annie_wang 已提交
625 626 627 628 629 630 631 632 633 634 635

createFile(uri: string, displayName: string) : Promise&lt;string&gt;

Creates a file in a directory. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
636 637
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
A
Annie_wang 已提交
638
| uri | string | Yes| URI of the destination directory for the file to create.|
A
Annie_wang 已提交
639
| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
A
Annie_wang 已提交
640 641 642 643 644

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
645
| Promise&lt;string&gt; | Promise used to return the URI of the file created.|
A
Annie_wang 已提交
646

A
Annie_wang 已提交
647 648 649 650
**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).

A
Annie_wang 已提交
651 652 653
**Example**

  ```js
A
Annie_wang 已提交
654 655 656 657
  // The media library URI is used as an example.
  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceUri = "datashare:///media/file/6";
A
Annie_wang 已提交
658 659 660
  let displayName = "file1"
  let fileUri = null;
  try {
A
Annie_wang 已提交
661
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
662 663 664 665 666
    fileUri = await fileAccessHelper.createFile(sourceUri, displayName)
    if (!fileUri) {
      console.error("createFile return undefined object");
      return;
    }
A
Annie_wang 已提交
667
    console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri));
A
Annie_wang 已提交
668
  } catch (error) {
A
Annie_wang 已提交
669 670 671 672
    console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
673
### createFile
A
Annie_wang 已提交
674

A
Annie_wang 已提交
675
createFile(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
A
Annie_wang 已提交
676 677 678 679 680 681 682 683 684

Creates a file in a directory. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
685 686
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
A
Annie_wang 已提交
687
| uri | string | Yes| URI of the destination directory for the file to create.|
A
Annie_wang 已提交
688
| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
A
Annie_wang 已提交
689 690 691 692 693
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the file created.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

**Example**

  ```js
  // The media library URI is used as an example.
  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceUri = "datashare:///media/file/6";
  let displayName = "file1"
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.createFile(sourceUri, displayName, function (err, fileUri) {
      if (err) {
        console.error("Failed to createFile in async, errCode:" + err.code + ", errMessage:" + err.message);
        return;
      }
      console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri));
    });
  } catch (error) {
    console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
714 715 716
  };
  ```

A
Annie_wang 已提交
717
### mkDir
A
Annie_wang 已提交
718 719 720

mkDir(parentUri: string, displayName: string) : Promise&lt;string&gt;

A
Annie_wang 已提交
721
Creates a directory. This API uses a promise to return the result.
A
Annie_wang 已提交
722 723 724 725 726 727 728

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
729 730
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
A
Annie_wang 已提交
731
| parentUri | string | Yes| URI of the destination directory for the directory to create.|
A
Annie_wang 已提交
732
| displayName | string | Yes| Name of the directory to create.|
A
Annie_wang 已提交
733 734 735 736 737

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
738
| Promise&lt;string&gt; | Promise used to return the URI of the directory created.|
A
Annie_wang 已提交
739

A
Annie_wang 已提交
740 741 742 743
**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).

A
Annie_wang 已提交
744 745 746
**Example**

  ```js
A
Annie_wang 已提交
747 748 749 750
  // The media library URI is used as an example.
  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceUri = "datashare:///media/file/6";
A
Annie_wang 已提交
751 752 753
  let dirName = "dirTest"
  let dirUri = null;
  try {
A
Annie_wang 已提交
754
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
755 756 757 758 759
    dirUri = await fileAccessHelper.mkDir(sourceUri, dirName)
    if (!dirUri) {
      console.error("mkDir return undefined object");
      return;
    }
A
Annie_wang 已提交
760
    console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri));
A
Annie_wang 已提交
761
  } catch (error) {
A
Annie_wang 已提交
762 763 764 765
    console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
766
### mkDir
A
Annie_wang 已提交
767

A
Annie_wang 已提交
768
mkDir(parentUri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
A
Annie_wang 已提交
769

A
Annie_wang 已提交
770
Creates a directory. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
771 772 773 774 775 776 777

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
778 779
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
A
Annie_wang 已提交
780
| parentUri | string | Yes| URI of the destination directory for the directory to create.|
A
Annie_wang 已提交
781
| displayName | string | Yes| Name of the directory to create.|
A
Annie_wang 已提交
782 783 784 785 786
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the directory created.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806

**Example**

  ```js
  // The media library URI is used as an example.
  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceUri = "datashare:///media/file/6";
  let dirName = "dirTest"
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.mkDir(sourceUri, dirName, function (err, dirUri) {
      if (err) {
        console.error("Failed to mkDir in async, errCode:" + err.code + ", errMessage:" + err.message);
        return;
      }
      console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri));
    });
  } catch (error) {
    console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
807 808 809
  };
  ```

A
Annie_wang 已提交
810
### openFile
A
Annie_wang 已提交
811

A
Annie_wang 已提交
812
openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;
A
Annie_wang 已提交
813 814 815 816 817 818 819 820 821

Opens a file. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
822 823 824 825
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file to open.|
| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
A
Annie_wang 已提交
826 827 828 829 830

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
831 832 833 834 835
| Promise&lt;number&gt; | Promise used to return the file descriptor (FD) of the file opened.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
836 837 838 839

**Example**

  ```js
A
Annie_wang 已提交
840
  // The media library URI is used as an example.
A
Annie_wang 已提交
841
  // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
A
Annie_wang 已提交
842 843
  // You can use the URI obtained.
  let targetUri  = "datashare:///media/file/100";
A
Annie_wang 已提交
844
  try {
A
Annie_wang 已提交
845 846 847
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    let fd = await fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ);
  } catch (error) {
A
Annie_wang 已提交
848 849 850 851
    console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
852
### openFile
A
Annie_wang 已提交
853

A
Annie_wang 已提交
854
openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : void
A
Annie_wang 已提交
855 856 857 858 859 860 861 862 863

Opens a file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
864 865 866 867
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file to open.|
| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
A
Annie_wang 已提交
868 869 870 871 872
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the FD of the file opened.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
873 874 875 876 877

**Example**

  ```js
  // The media library URI is used as an example.
A
Annie_wang 已提交
878
  // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
A
Annie_wang 已提交
879 880 881 882 883 884 885 886 887 888 889 890 891
  // You can use the URI obtained.
  let targetUri  = "datashare:///media/file/100";
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ, function (err, fd) {
      if (err) {
        console.error("Failed to openFile in async, errCode:" + err.code + ", errMessage:" + err.message);
        return;
      }
      console.log("openFile sucess, fd: " + fd);
    });
  } catch (error) {
    console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
892 893 894
  };
  ```

A
Annie_wang 已提交
895
### delete
A
Annie_wang 已提交
896 897 898

delete(uri: string) : Promise&lt;number&gt;

A
Annie_wang 已提交
899
Deletes a file or directory. This API uses a promise to return the result.
A
Annie_wang 已提交
900 901 902 903 904 905 906

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
907 908 909
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or directory to delete.|
A
Annie_wang 已提交
910 911 912 913 914 915 916

**Return value**

| Type| Description|
| --- | -- |
| Promise&lt;number&gt | Promise used to return the result.|

A
Annie_wang 已提交
917 918 919 920
**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).

A
Annie_wang 已提交
921 922 923
**Example**

  ```js
A
Annie_wang 已提交
924
  // The media library URI is used as an example.
A
Annie_wang 已提交
925
  // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
A
Annie_wang 已提交
926 927
  // You can use the URI obtained.
  let targetUri = "datashare:///media/file/100";
A
Annie_wang 已提交
928
  try {
A
Annie_wang 已提交
929
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
930 931 932
    let code = await fileAccessHelper.delete(targetUri);
    if (code != 0)
      console.error("delete failed, code " + code);
A
Annie_wang 已提交
933
  } catch (error) {
A
Annie_wang 已提交
934 935 936 937
    console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
938
### delete
A
Annie_wang 已提交
939

A
Annie_wang 已提交
940
delete(uri: string, callback: AsyncCallback&lt;number&gt;) : void
A
Annie_wang 已提交
941

A
Annie_wang 已提交
942
Deletes a file or directory. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
943 944 945 946 947 948 949

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
950 951 952
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or directory to delete.|
A
Annie_wang 已提交
953 954 955 956 957
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
958 959 960 961 962

**Example**

  ```js
  // The media library URI is used as an example.
A
Annie_wang 已提交
963
  // In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
A
Annie_wang 已提交
964 965 966 967 968 969 970 971 972 973 974 975 976
  // You can use the URI obtained.
  let targetUri = "datashare:///media/file/100";
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.delete(targetUri, function (err, code) {
      if (err) {
        console.error("Failed to delete in async, errCode:" + err.code + ", errMessage:" + err.message);
        return;
      }
      console.log("delete sucess, code: " + code);
    });
  } catch (error) {
    console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
977 978 979
  };
  ```

A
Annie_wang 已提交
980
### move
A
Annie_wang 已提交
981 982 983

move(sourceFile: string, destFile: string) : Promise&lt;string&gt;

A
Annie_wang 已提交
984
Moves a file or directory. This API uses a promise to return the result. Currently, this API does not support move of files or directories across devices.
A
Annie_wang 已提交
985 986 987 988 989 990 991

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
992 993 994
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFile | string | Yes| URI of the file or directory to move.|
A
Annie_wang 已提交
995
| destFile | string | Yes| URI of the destination directory, to which the file or directory will be moved.|
A
Annie_wang 已提交
996 997 998 999 1000

**Return value**

| Type| Description|
| ----- | ------ |
A
Annie_wang 已提交
1001
| Promise&lt;string&gt; | Promise used to return the URI of the file or directory in the destination directory.|
A
Annie_wang 已提交
1002

A
Annie_wang 已提交
1003 1004 1005 1006
**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).

A
Annie_wang 已提交
1007 1008 1009
**Example**

  ```js
A
Annie_wang 已提交
1010
  // The media library URI is used as an example.
A
Annie_wang 已提交
1011
  // In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
A
Annie_wang 已提交
1012 1013 1014
  // You can use the URI obtained.
  let sourceFile = "datashare:///media/file/102";
  let destFile = "datashare:///media/file/101";
A
Annie_wang 已提交
1015
  try {
A
Annie_wang 已提交
1016
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
1017
    let fileUri = await fileAccessHelper.move(sourceFile, destFile);
A
Annie_wang 已提交
1018 1019 1020 1021 1022 1023
    console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
  } catch (error) {
    console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
1024
### move
A
Annie_wang 已提交
1025

A
Annie_wang 已提交
1026
move(sourceFile: string, destFile: string, callback: AsyncCallback&lt;string&gt;) : void
A
Annie_wang 已提交
1027

A
Annie_wang 已提交
1028
Moves a file or directory. This API uses an asynchronous callback to return the result. Currently, this API does not support move of files or directories across devices.
A
Annie_wang 已提交
1029 1030 1031 1032 1033 1034 1035

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
1036 1037 1038
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFile | string | Yes| URI of the file or directory to move.|
A
Annie_wang 已提交
1039 1040 1041 1042 1043 1044
| destFile | string | Yes| URI of the destination directory, to which the file or directory will be moved.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the file or directory in the destination directory.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
1045 1046 1047 1048 1049

**Example**

  ```js
  // The media library URI is used as an example.
A
Annie_wang 已提交
1050
  // In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
A
Annie_wang 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
  // You can use the URI obtained.
  let sourceFile = "datashare:///media/file/102";
  let destFile = "datashare:///media/file/101";
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.move(sourceFile, destFile, function (err, fileUri) {
      if (err) {
        console.error("Failed to move in async, errCode:" + err.code + ", errMessage:" + err.message);
        return;
      }
      console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
    });
A
Annie_wang 已提交
1063
  } catch (error) {
A
Annie_wang 已提交
1064
    console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
1065 1066 1067
  };
  ```

A
Annie_wang 已提交
1068
### rename
A
Annie_wang 已提交
1069 1070 1071

rename(uri: string, displayName: string) : Promise&lt;string&gt;

A
Annie_wang 已提交
1072
Renames a file or directory. This API uses a promise to return the result.
A
Annie_wang 已提交
1073 1074 1075 1076 1077 1078 1079

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
1080 1081 1082 1083
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or directory to rename.|
| displayName | string | Yes| New name of the file or directory, which can contain the file name extension.|
A
Annie_wang 已提交
1084 1085 1086 1087 1088

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
1089
| Promise&lt;string&gt; | Promise used to return the URI of the renamed file or directory.|
A
Annie_wang 已提交
1090

A
Annie_wang 已提交
1091 1092 1093 1094
**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).

A
Annie_wang 已提交
1095 1096 1097
**Example**

  ```js
A
Annie_wang 已提交
1098 1099 1100 1101
  // The media library URI is used as an example.
  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceDir = "datashare:///media/file/100";
A
Annie_wang 已提交
1102
  try {
A
Annie_wang 已提交
1103
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
1104
    let DestDir = await fileAccessHelper.rename(sourceDir, "testDir");
A
Annie_wang 已提交
1105
    console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
A
Annie_wang 已提交
1106
  } catch (error) {
A
Annie_wang 已提交
1107 1108 1109 1110
    console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
1111
### rename
A
Annie_wang 已提交
1112

A
Annie_wang 已提交
1113
rename(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
A
Annie_wang 已提交
1114

A
Annie_wang 已提交
1115
Renames a file or directory. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1116 1117 1118 1119 1120 1121 1122

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
1123 1124 1125 1126
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or directory to rename.|
| displayName | string | Yes| New name of the file or directory, which can contain the file name extension.|
A
Annie_wang 已提交
1127 1128 1129 1130 1131
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the renamed file or directory.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150

**Example**

  ```js
  // The media library URI is used as an example.
  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceDir = "datashare:///media/file/100";
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.rename(sourceDir, "testDir", function (err, DestDir) {
      if (err) {
        console.error("Failed to rename in async, errCode:" + err.code + ", errMessage:" + err.message);
        return;
      }
      console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
    });
  } catch (error) {
    console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
1151 1152 1153
  };
  ```

A
Annie_wang 已提交
1154
### access
A
Annie_wang 已提交
1155 1156 1157

access(sourceFileUri: string) : Promise&lt;boolean&gt;

A
Annie_wang 已提交
1158
Checks whether a file or directory exists. This API uses a promise to return the result.
A
Annie_wang 已提交
1159 1160 1161 1162 1163 1164 1165

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
1166 1167
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
A
Annie_wang 已提交
1168
| sourceFileUri | string | Yes| URI of the file or directory to check.|
A
Annie_wang 已提交
1169 1170 1171 1172 1173 1174 1175

**Return value**

| Type| Description|
| --- | -- |
| Promise&lt;boolean&gt; | Promise used to return the result.|

A
Annie_wang 已提交
1176 1177 1178 1179
**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).

A
Annie_wang 已提交
1180 1181 1182
**Example**

  ```js
A
Annie_wang 已提交
1183 1184 1185 1186
  // The media library URI is used as an example.
  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceDir = "datashare:///media/file/100";
A
Annie_wang 已提交
1187
  try {
A
Annie_wang 已提交
1188
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
1189 1190 1191 1192 1193
    let existJudgment = await fileAccessHelper.access(sourceDir);
    if (existJudgment)
      console.log("sourceDir exists");
    else
      console.log("sourceDir does not exist");
A
Annie_wang 已提交
1194
  } catch (error) {
A
Annie_wang 已提交
1195 1196 1197 1198
    console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
1199
### access
A
Annie_wang 已提交
1200

A
Annie_wang 已提交
1201
access(sourceFileUri: string, callback: AsyncCallback&lt;boolean&gt;) : void
A
Annie_wang 已提交
1202

A
Annie_wang 已提交
1203
Checks whether a file or directory exists. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1204 1205 1206 1207 1208 1209 1210

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
1211 1212
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
A
Annie_wang 已提交
1213 1214 1215 1216 1217 1218
| sourceFileUri | string | Yes| URI of the file or directory to check.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback invoked to return the result.|

**Error codes**

For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
A
Annie_wang 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240

**Example**

  ```js
  // The media library URI is used as an example.
  // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceDir = "datashare:///media/file/100";
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.access(sourceDir, function (err, existJudgment) {
      if (err) {
        console.error("Failed to access in async, errCode:" + err.code + ", errMessage:" + err.message);
        return;
      }
      if (existJudgment)
        console.log("sourceDir exists");
      else
        console.log("sourceDir does not exist");
    });
  } catch (error) {
    console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
1241 1242 1243
  };
  ```

A
Annie_wang 已提交
1244
### getFileInfoFromUri<sup>10+</sup>
A
Annie_wang 已提交
1245

A
Annie_wang 已提交
1246
getFileInfoFromUri(uri: string) : Promise\<FileInfo>
A
Annie_wang 已提交
1247

A
Annie_wang 已提交
1248
Obtains a **FileInfo** object based on the specified URI. This API uses a promise to return the result.
A
Annie_wang 已提交
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or directory.|

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
1264
| Promise\<[FileInfo](#fileinfo)> | Promise used to return the **FileInfo** object obtained.|
A
Annie_wang 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280

**Example**

  ```js
  // The media library URI is used as an example.
  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceUri = "datashare:///media/file/6";
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    let fileInfo = await fileAccessHelper.getFileInfoFromUri(sourceUri);
  } catch (error) {
    console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
1281
### getFileInfoFromUri<sup>10+</sup>
A
Annie_wang 已提交
1282

A
Annie_wang 已提交
1283
getFileInfoFromUri(uri: string, callback: AsyncCallback\<FileInfo>) : void
A
Annie_wang 已提交
1284

A
Annie_wang 已提交
1285
Obtains a **FileInfo** object based on the specified URI. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1286 1287 1288 1289 1290 1291 1292

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

A
Annie_wang 已提交
1293 1294 1295 1296
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | uri | string | Yes| URI of the file or directory.|
  | callback | AsyncCallback&lt;[FileInfo](#fileinfo)&gt; | Yes| Callback invoked to return the **FileInfo** object obtained.|
A
Annie_wang 已提交
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319

**Example**

  ```js
  // The media library URI is used as an example.
  // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceUri = "datashare:///media/file/6";
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.getFileInfoFromUri(sourceUri, function (err, fileInfo) {
      if (err) {
        console.error("Failed to getFileInfoFromUri in async, errCode:" + err.code + ", errMessage:" + err.message);
        return;
      }
      console.log("getFileInfoFromUri success, fileInfo: " + JSON.stringify(fileInfo));
    });
  } catch (error) {
    console.error("getFileInfoFromUri failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```


A
Annie_wang 已提交
1320
### getFileInfoFromRelativePath<sup>10+</sup>
A
Annie_wang 已提交
1321

A
Annie_wang 已提交
1322
getFileInfoFromRelativePath(relativePath: string) : Promise\<FileInfo>
A
Annie_wang 已提交
1323

A
Annie_wang 已提交
1324
Obtains a **FileInfo** object based on the **relativePath**. This API uses a promise to return the result.
A
Annie_wang 已提交
1325 1326 1327 1328 1329 1330 1331 1332 1333

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
A
Annie_wang 已提交
1334
| relativePath | string | Yes| Relative path of the file or directory.|
A
Annie_wang 已提交
1335 1336 1337 1338 1339

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
1340
| Promise\<[FileInfo](#fileinfo)> | Promise used to return the **FileInfo** object obtained.|
A
Annie_wang 已提交
1341 1342 1343 1344

**Example**

  ```js
A
Annie_wang 已提交
1345 1346
  // The relative path of the Media Library is used as an example.
  // In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
A
Annie_wang 已提交
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
  // You can use the relativePath obtained.
  let relativePath = "Download/";
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    let fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(relativePath);
  } catch (error) {
    console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
1357
### getFileInfoFromRelativePath<sup>10+</sup>
A
Annie_wang 已提交
1358

A
Annie_wang 已提交
1359
getFileInfoFromRelativePath(relativePath: string, callback: AsyncCallback\<FileInfo>) : void
A
Annie_wang 已提交
1360

A
Annie_wang 已提交
1361
Obtains a **FileInfo** object based on the **relativePath**. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1362 1363 1364 1365 1366 1367 1368 1369 1370

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
A
Annie_wang 已提交
1371 1372
| relativePath | string | Yes| Relative path of the file or directory.|
| callback | AsyncCallback&lt;[FileInfo](#fileinfo)&gt; | Yes| Callback invoked to return the **FileInfo** object obtained.|
A
Annie_wang 已提交
1373 1374 1375 1376

**Example**

  ```js
A
Annie_wang 已提交
1377 1378
  // The relative path of the Media Library is used as an example.
  // In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
A
Annie_wang 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
  // You can use the relativePath obtained.
  let relativePath = "Download/";
  try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.getFileInfoFromRelativePath(relativePath, function (err, fileInfo) {
      if (err) {
        console.error("Failed to getFileInfoFromRelativePath in async, errCode:" + err.code + ", errMessage:" + err.message);
        return;
      }
      console.log("getFileInfoFromRelativePath success, fileInfo: " + JSON.stringify(fileInfo));
    });
  } catch (error) {
    console.error("getFileInfoFromRelativePath failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

A
Annie_wang 已提交
1395
### getThumbnail<sup>10+</sup>
A
Annie_wang 已提交
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415

getThumbnail(uri: string, size: image.Size) : Promise&lt;image.PixelMap&gt;

Obtains the **Pixelmap** object of a media file based on the specified URI and size. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

| Name| Type                               | Mandatory| Description       |
| ------ | ----------------------------------- | ---- | ----------- |
| uri    | string                              | Yes  | URI of the media file.|
| size   | [image.Size](js-apis-image.md#size) | Yes  | Size of the thumbnail. |

**Return value**

| Type                         | Description              |
| :---------------------------- | :----------------- |
A
Annie_wang 已提交
1416
| Promise&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise used to return the **Pixelmap** object obtained.|
A
Annie_wang 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

**Example**

```js
// The media library URI is used as an example.
// In the sample code, targetUri indicates a media file (image, audio, or video) in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
let targetUri = "datashare:///media/image/100";
let size = { width: 128, height: 128 };
try {
  // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
  let pixelMap = await fileAccessHelper.getThumbnail(targetUri, size);
  let imageInfo = await pixelMap.getImageInfo();    
  console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width);
  console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height);
} catch (error) {
  console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message);
};
```

A
Annie_wang 已提交
1437
### getThumbnail<sup>10+</sup>
A
Annie_wang 已提交
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452

 getThumbnail(uri: string, size: image.Size, callback: AsyncCallback&lt;image.PixelMap&gt;) : void

Obtains the **Pixelmap** object of a media file based on the specified URI and size. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

| Name  | Type                               | Mandatory| Description              |
| -------- | ----------------------------------- | ---- | ------------------ |
| uri      | string                              | Yes  | URI of the media file.       |
| size     | [image.Size](js-apis-image.md#size) | Yes  | Size of the thumbnail.        |
A
Annie_wang 已提交
1453
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes  | Callback invoked to return the **Pixelmap** object obtained.|
A
Annie_wang 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478

**Example**

```js
// The media library URI is used as an example.
// In the sample code, targetUri indicates a media file (image, audio, or video) in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
let targetUri = "datashare:///media/image/100";
let size = { width: 128, height: 128 };
try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.getThumbnail(targetUri, size, async(err, pixelMap) => {
        if (err) {
            console.error("Failed to getThumbnail in async, errCode:" + err.code + ", errMessage:" + err.message);
            return;
        }
        let imageInfo = await pixelMap.getImageInfo();
        console.log("getThumbnail sucess, pixelMap.width: " + imageInfo.size.width);
        console.log("getThumbnail sucess, pixelMap.height: " + imageInfo.size.height);
    });
} catch (error) {
    console.error("getThumbnail failed, errCode:" + error.code + ", errMessage:" + error.message);
};
```

A
Annie_wang 已提交
1479
### query<sup>10+</sup>
A
Annie_wang 已提交
1480

A
Annie_wang 已提交
1481
query(uri:string, metaJson: string) : Promise&lt;string&gt;
A
Annie_wang 已提交
1482

A
Annie_wang 已提交
1483
Queries the attribute information about a file or directory based on the URI. This API uses a promise to return the result.
A
Annie_wang 已提交
1484 1485 1486 1487 1488

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

A
Annie_wang 已提交
1489 1490 1491 1492 1493 1494 1495
**Parameters**

| Name  | Type  | Mandatory| Description                                                |
| -------- | ------ | ---- | ---------------------------------------------------- |
| uri      | string | Yes  | URI of the file or directory (obtained from [FileInfo](#fileinfo)).|
| metaJson | string | Yes  | Attribute [FILEKEY](#filekey10) to query.       |

A
Annie_wang 已提交
1496 1497
**Return value**

A
Annie_wang 已提交
1498 1499 1500 1501 1502
| Type                 | Description                            |
| :-------------------- | :------------------------------- |
| Promise&lt;string&gt; | Promised used to return the attribute queried and the value obtained.|

**Example**
A
Annie_wang 已提交
1503

A
Annie_wang 已提交
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
```js
var imageFileRelativePath = "Download/queryTest/image/01.jpg";
var jsonStrSingleRelativepath = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    var fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath);
    let queryResult = await fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath);
    console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path);
} catch (error) {
     console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message);
};
```
A
Annie_wang 已提交
1516

A
Annie_wang 已提交
1517
### query<sup>10+</sup>
A
Annie_wang 已提交
1518

A
Annie_wang 已提交
1519 1520 1521
query(uri:string, metaJson: string, callback: AsyncCallback&lt;string&gt;) : void

Queries the attribute information about a file or directory based on the URI. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1522 1523 1524 1525 1526

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

A
Annie_wang 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
**Parameters**

| Name  | Type                       | Mandatory| Description                                                |
| -------- | --------------------------- | ---- | ---------------------------------------------------- |
| uri      | string | Yes  | URI of the file or directory (obtained from [FileInfo](#fileinfo)).|
| metaJson | string | Yes  | Attribute [FILEKEY](#filekey10) to query.       |
| callback | AsyncCallback&lt;string&gt; | Yes  | Callback invoked to return the attribute queried and the value obtained.                    |

**Example**

```js
var imageFileRelativePath = "Download/queryTest/image/01.jpg";
var jsonStrSingleRelativepath = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    var fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath);
    fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath, (err, queryResult)=>{
        if (err) {
            console.log("query_file_single faf query Failed, errCode:" + err.code + ", errMessage:" + err.message);
            return;
        }
        console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path);
    })
} catch (error) {
   console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message);
};
```

### copy<sup>10+</sup>

copy(sourceUri: string, destUri: string, force?: boolean) : Promise&lt;Array&lt;CopyResult&gt;&gt;

Copies a file or directory. This API uses a promise to return the result.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

**Parameters**

| Name   | Type   | Mandatory| Description                                                        |
| --------- | ------- | ---- | ------------------------------------------------------------ |
| sourceUri | string  | Yes  | URI of the file or directory to copy, for example, **datashare:///media/file/102**. |
| destUri   | string  | Yes  | URI of the destination directory, for example, **datashare:///media/file/101**.         |
| 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.|

A
Annie_wang 已提交
1573 1574
**Return value**

A
Annie_wang 已提交
1575 1576 1577
| Type                                                   | Description                                                        |
| :------------------------------------------------------ | :----------------------------------------------------------- |
| Promise&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Promise used to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
A
Annie_wang 已提交
1578

A
Annie_wang 已提交
1579
Example 1: Copy a file with **force** unspecified.
A
Annie_wang 已提交
1580

A
Annie_wang 已提交
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
```js
// The media library URI is used as an example.
// 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.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    let copyResult = await fileAccessHelper.copy(sourceFile, destFile);
    if (copyResult.length === 0) {
        console.log("copy success");
    } else {
        for (let i = 0; i < copyResult.length; i++) {
            console.error("errCode" + copyResult[i].errCode);
            console.error("errMsg" + copyResult[i].errMsg);
            console.error("sourceUri" + copyResult[i].sourceUri);
            console.error("destUri" + copyResult[i].destUri);
        }
    }
} catch (error) {
    console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```

Example 2: Copy a file or directory when **force** set to **true**.

```js
// The media library URI is used as an example.
// 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.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    let copyResult = await fileAccessHelper.copy(sourceFile, destFile, true);
    if (copyResult.length === 0) {
        console.log("copy success");
    } else {
        for (let i = 0; i < copyResult.length; i++) {
            console.error("errCode" + copyResult[i].errCode);
            console.error("errMsg" + copyResult[i].errMsg);
            console.error("sourceUri" + copyResult[i].sourceUri);
            console.error("destUri" + copyResult[i].destUri);
        }
    }
} catch (error) {
    console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```

### copy<sup>10+</sup>

copy(sourceUri: string, destUri: string, callback: AsyncCallback&lt;Array&lt;CopyResult&gt;&gt;) : void

Copies a file or directory. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1636 1637 1638 1639 1640

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

A
Annie_wang 已提交
1641
**Parameters**
A
Annie_wang 已提交
1642

A
Annie_wang 已提交
1643 1644 1645 1646 1647
| Name   | Type                                            | Mandatory| Description                                                        |
| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| sourceUri | string                                           | Yes  | URI of the file or directory to copy, for example, **datashare:///media/file/102**. |
| destUri   | string                                           | Yes  | URI of the destination directory, for example, **datashare:///media/file/101**.         |
| callback  | AsyncCallback&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Yes  | Callback invoked to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
A
Annie_wang 已提交
1648

A
Annie_wang 已提交
1649
**Example**
A
Annie_wang 已提交
1650

A
Annie_wang 已提交
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
```js
// The media library URI is used as an example.
// 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.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.copy(sourceFile, destFile, async (err, copyResult) => {
        if (err) {
            console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message);
            return;
        }
        if (copyResult.length === 0) {
            console.log("copy success");
        } else {
            for (let i = 0; i < copyResult.length; i++) {
                console.error("errCode" + copyResult[i].errCode);
                console.error("errMsg" + copyResult[i].errMsg);
                console.error("sourceUri" + copyResult[i].sourceUri);
                console.error("destUri" + copyResult[i].destUri);
            }
        }
    });
} catch (error) {
    console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```

### copy<sup>10+</sup>

copy(sourceUri: string, destUri: string, force: boolean, callback: AsyncCallback&lt;Array&lt;CopyResult&gt;&gt;) : void

Copies a file or directory. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
1685 1686 1687 1688 1689

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

A
Annie_wang 已提交
1690
**Parameters**
A
Annie_wang 已提交
1691

A
Annie_wang 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
| Name   | Type                                            | Mandatory| Description                                                        |
| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| sourceUri | string                                           | Yes  | URI of the file or directory to copy, for example, **datashare:///media/file/102**. |
| destUri   | string                                           | Yes  | URI of the destination directory, for example, **datashare:///media/file/101**.         |
| 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.|
| callback  | AsyncCallback&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Yes  | Callback invoked to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|

**Example**

```js
// The media library URI is used as an example.
// 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.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
try {
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
    fileAccessHelper.copy(sourceFile, destFile, true, async (err, copyResult) => {
        if (err) {
            console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message);
            return;
        }
        if (copyResult.length === 0) {
            console.log("copy success");
        } else {
            for (let i = 0; i < copyResult.length; i++) {
                console.error("errCode" + copyResult[i].errCode);
                console.error("errMsg" + copyResult[i].errMsg);
                console.error("sourceUri" + copyResult[i].sourceUri);
                console.error("destUri" + copyResult[i].destUri);
            }
        }
    });
} catch (error) {
    console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```

## CopyResult<sup>10+</sup>

Defines the information returned when the file copy operation fails. If the copy operation is successful, no information is returned.

**System capability**: SystemCapability.FileManagement.UserFileService

**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER

| Name     | Type  | Readable| Writable| Description               |
| --------- | ------ | ---- | ---- | ----------------- |
| sourceUri | string | Yes  | No  | URI of the source file or directory.                                        |
| destUri   | string | Yes  | No  | URI of the conflict file. If the error is not caused by a conflict, **destUri** is empty.|
| errCode   | number | Yes  | No  | Error code.                                                |
| errMsg    | string | Yes  | No  | Error information.                                              |
A
Annie_wang 已提交
1744 1745 1746

## OPENFLAGS

A
Annie_wang 已提交
1747 1748 1749
Enumerates the file open modes.

**Model restriction**: This API can be used only in the stage model.
A
Annie_wang 已提交
1750 1751 1752 1753 1754 1755 1756 1757

**System capability**: SystemCapability.FileManagement.UserFileService

| Name| Value| Description|
| ----- | ------ | ------ |
| READ | 0o0 | Read mode.|
| WRITE | 0o1 | Write mode.|
| WRITE_READ | 0o2 | Read/Write mode.|
A
Annie_wang 已提交
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776

## FILEKEY<sup>10+</sup>

Enumerates the keys of the file attributes to query.

**Model restriction**: This API can be used only in the stage model.

**System capability**: SystemCapability.FileManagement.UserFileService

| Name         | Value           | Description                               |
| ------------- | ------------- | ----------------------------------- |
| DISPLAY_NAME  | 'display_name'  | Name of the file.                             |
| DATE_ADDED    | 'date_added'   | Date when the file was created, for example, **1501925454**.     |
| DATE_MODIFIED | 'date_modified' | Date when a file was modified, for example, **1665310670**.     |
| RELATIVE_PATH | 'relative_path' | Relative path of the file, for example, **Pictures/Screenshots/**.|
| FILE_SIZE     | 'size'          | Size of a file, in bytes.       |
| WIDTH         | 'width'         | Width of the image file, in pixels.       |
| HEIGHT        | 'height'        | Height of the image file, in pixels.       |
| DURATION      | 'duration'      | Duration of the audio or video file, in milliseconds. |