js-apis-fileAccess.md 36.7 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 is a framework for accessing and operating user files based on the Extension ability mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of file access and management APIs for system applications. The media library service allows access to user files on local devices 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 7

>**NOTE**
>
>- 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.
A
Annie_wang 已提交
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 **Files**.
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 18 19 20 21 22 23
```

## fileAccess.getFileAccessAbilityInfo

getFileAccessAbilityInfo( ) : Promise<Array<Want>>

Obtains information about all wants with **extension** set to **fileAcesss** in the system. A want is a basic communication component used to start services. This API uses a promise to return the result.

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

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

**Return value**

A
Annie_wang 已提交
28 29 30
  | Type| Description|
  | --- | -- |
  | Promise<Array<Want>> | Promise used to return the **want** information obtained.|
A
Annie_wang 已提交
31 32 33 34 35 36 37 38 39 40

**Example**

  ```js
  async getFileAccessAbilityInfo() {
    let wantInfos = [];
    try {
      wantInfos = await fileAccess.getFileAccessAbilityInfo();
      console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos));
    } catch (error) {
A
Annie_wang 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
      console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message);
    }
  }
  ```

## fileAccess.getFileAccessAbilityInfo

getFileAccessAbilityInfo(callback: AsyncCallback<Array<Want>>): void;

Obtains information about all wants with **extension** set to **fileAcesss** in the system. A want is a basic communication component used to start services. This API uses an asynchronous callback to return the result.

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

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

**Parameters**

  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | callback | AsyncCallback<Array<Want>> | Yes| Promise used to return the **want** information obtained.|

**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 已提交
76 77 78 79 80 81 82 83 84 85 86 87
    }
  }
  ```

## fileAccess.createFileAccessHelper

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

Synchronously creates a **Helper** object to connect to the specified wants. The **Helper** object provides file access and management capabilities.

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

A
Annie_wang 已提交
88
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
A
Annie_wang 已提交
89 90 91

**Parameters**

A
Annie_wang 已提交
92 93 94 95
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | context | Context | Yes| Context of the ability.|
  | wants | Array<Want> | Yes| Wants to connect.|
A
Annie_wang 已提交
96 97 98

**Return value**

A
Annie_wang 已提交
99 100 101
  | Type| Description|
  | --- | -- |
  | FileAccessHelper | **Helper** object created.|
A
Annie_wang 已提交
102 103 104 105 106

**Example**

  ```js
  createFileAccessHelper() {
A
Annie_wang 已提交
107 108
    let fileAccessHelper = null;
    / / Obtain wantInfos by using getFileAccessAbilityInfo().
A
Annie_wang 已提交
109
    // Create a helper object to interact with the media library service only.
A
Annie_wang 已提交
110 111 112 113 114 115 116
    let wantInfos = [
      {
        "bundleName": "com.ohos.medialibrary.medialibrarydata",
        "abilityName": "FileExtensionAbility",
      },
    ]
    try {
A
Annie_wang 已提交
117
      // this.context is passed by MainAbility.
A
Annie_wang 已提交
118 119
      fileAccessHelper = fileAccess.createFileAccessHelper(this.context, wantInfos);
      if (!fileAccessHelper)
A
Annie_wang 已提交
120 121
        console.error("createFileAccessHelper interface returns an undefined object");
    } catch (error) {
A
Annie_wang 已提交
122
      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
123 124 125 126 127 128 129 130
    }
  }
  ```

## fileAccess.createFileAccessHelper

createFileAccessHelper(context: Context) : FileAccessHelper

A
Annie_wang 已提交
131
Synchronously creates a **Helper** object to connect to all file management services in the system.
A
Annie_wang 已提交
132 133 134

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

A
Annie_wang 已提交
135
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
A
Annie_wang 已提交
136 137 138

**Parameters**

A
Annie_wang 已提交
139 140 141
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | context | Context | Yes| Context of the ability.|
A
Annie_wang 已提交
142 143 144

**Return value**

A
Annie_wang 已提交
145 146 147
  | Type| Description|
  | --- | -- |
  | FileAccessHelper | **Helper** object created.|
A
Annie_wang 已提交
148 149 150 151 152 153 154 155

**Example**

  ```js
  createFileAccessHelper() {
    let fileAccesssHelperAllServer = null;
    // Create a Helper object to interact with all file management services configured with fileAccess in the system.
    try {
A
Annie_wang 已提交
156
      // this.context is passed by MainAbility.
A
Annie_wang 已提交
157 158 159 160
      fileAccesssHelperAllServer = fileAccess.createFileAccessHelper(this.context);
      if (!fileAccesssHelperAllServer)
        console.error("createFileAccessHelper interface returns an undefined object");
    } catch (error) {
A
Annie_wang 已提交
161
      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
162 163 164 165 166 167 168 169
    }
  }
  ```

## FileAccessHelper.getRoots

getRoots( ) : Promise<RootIterator>

A
Annie_wang 已提交
170
Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which
A
Annie_wang 已提交
171 172 173 174 175 176 177 178
returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext).

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

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

**Return value**

A
Annie_wang 已提交
179 180 181
  | Type| Description|
  | --- | -- |
  | Promise<RootIterator> | Promise used to return the **RootIterator** object obtained.|
A
Annie_wang 已提交
182 183 184 185 186 187 188 189 190

**Example**

  ```js
  async getRoots() {
    let rootIterator = null;
    let rootinfos = [];
    let isDone = false;
    try {
A
Annie_wang 已提交
191 192
      // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
      rootIterator = await fileAccessHelper.getRoots();
A
Annie_wang 已提交
193 194 195 196 197 198 199 200 201 202 203 204
      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) {
A
Annie_wang 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
      console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
    }
  }
  ```

## FileAccessHelper.getRoots

getRoots(callback:AsyncCallback<RootIterator>) : void;

Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses an asynchronous callback to return the result.
The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo) through [next()](#rootiteratornext).

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

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

**Parameters**

  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | callback | AsyncCallback<RootIterator> | Yes| Promise used to return the **RootIterator** object obtained.|

**Example**

  ```js
  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 已提交
250 251 252 253 254 255 256 257
    }
  }
  ```

## RootInfo.listfile

listFile(filter?: Filter) : FileIterator

A
Annie_wang 已提交
258
Synchronously obtains the **FileIterator** object of the first-level files (file folder) matching the conditions of the filter from the device root node. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext).
A
Annie_wang 已提交
259 260 261 262 263 264 265

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

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

**Parameters**

A
Annie_wang 已提交
266 267 268
  | Name| Type| Mandatory| Description|
  | --- | --- | -- | -- |
  | filter | Filter | No| **Filter** object. |
A
Annie_wang 已提交
269 270 271 272


**Return value**

A
Annie_wang 已提交
273 274 275
  | Type| Description|
  | --- | -- |
  | FileIterator | **FileIterator** object obtained.|
A
Annie_wang 已提交
276 277 278 279

**Example**

  ```js
A
Annie_wang 已提交
280
  // Obtain rootInfos by using getRoots().
A
Annie_wang 已提交
281 282 283 284 285 286
  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
  let rootInfo = rootinfos[0];
  let fileInfos = [];
  let isDone = false;
  try {
    let fileIterator = rootInfo.listFile();
A
Annie_wang 已提交
287
    // listFile contains the filter implementation.
A
Annie_wang 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300
    // 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 已提交
301
    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
302 303 304 305 306 307 308
  }
  ```

## RootInfo.scanFile

scanFile(filter?: Filter) : FileIterator

A
Annie_wang 已提交
309
Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from the device root node synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext).
A
Annie_wang 已提交
310 311 312 313 314 315 316

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

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

**Parameters**

A
Annie_wang 已提交
317 318 319
  | Name| Type| Mandatory| Description|
  | --- | --- | -- | -- |
  | filter | Filter | No| **Filter** object. |
A
Annie_wang 已提交
320 321 322

**Return value**

A
Annie_wang 已提交
323 324 325
  | Type| Description|
  | --- | -- |
  | FileIterator | **FileIterator** object obtained.|
A
Annie_wang 已提交
326 327 328 329

**Example**

  ```js
A
Annie_wang 已提交
330
  // Obtain rootInfos by using getRoots().
A
Annie_wang 已提交
331
  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
A
Annie_wang 已提交
332
  let rootInfo = rootInfos[0];
A
Annie_wang 已提交
333 334 335
  let fileInfos = [];
  let isDone = false;
  try {
A
Annie_wang 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349
    let fileIterator = rootInfo.scanFile();
    // scanFile contains the filter implementation.
    // 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 已提交
350
  } catch (error) {
A
Annie_wang 已提交
351
    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
  }
  ```

## FileInfo.listfile

listFile(filter?: Filter) : FileIterator

Synchronously obtains the **FileIterator** object of the next-level files (file folders) matching the conditions of the filter from a directory. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext).

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

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

**Parameters**

A
Annie_wang 已提交
367 368 369
  | Name| Type| Mandatory| Description|
  | --- | --- | -- | -- |
  | filter | Filter | No| **Filter** object. |
A
Annie_wang 已提交
370 371 372

**Return value**

A
Annie_wang 已提交
373 374 375
  | Type| Description|
  | --- | -- |
  | FileIterator | **FileIterator** object obtained.|
A
Annie_wang 已提交
376 377 378 379 380

**Example**

  ```js
  // fileInfoDir specifies the target directory.
A
Annie_wang 已提交
381
  // let filter = { suffix : [".txt", ".jpg", ".xlsx"] };
A
Annie_wang 已提交
382 383 384 385 386
  let fileInfoDir = fileInfos[0];
  let subfileInfos = [];
  let isDone = false;
  try {
    let fileIterator = fileInfoDir.listFile();
A
Annie_wang 已提交
387
    // listFile contains the filter implementation.
A
Annie_wang 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400
    // 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);
    }
  } catch (error) {
A
Annie_wang 已提交
401
    console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
  }
  ```

## FileInfo.scanfile

scanFile(filter?: Filter) : FileIterator;

Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from a directory synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext).

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

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

**Parameters**

A
Annie_wang 已提交
417 418 419
  | Name| Type| Mandatory| Description|
  | --- | --- | -- | -- |
  | filter | Filter | No| **Filter** object. |
A
Annie_wang 已提交
420 421 422 423


**Return value**

A
Annie_wang 已提交
424 425 426
  | Type| Description|
  | --- | -- |
  | FileIterator | **FileIterator** object obtained.|
A
Annie_wang 已提交
427 428 429 430 431 432 433 434 435 436 437

**Example**

  ```js
  // fileInfoDir specifies the target directory.
  // let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
  let fileInfoDir = fileInfos[0];
  let subfileInfos = [];
  let isDone = false;
  try {
    let fileIterator = fileInfoDir.scanFile();
A
Annie_wang 已提交
438
    // scanFile contains the filter implementation.
A
Annie_wang 已提交
439 440 441 442 443 444 445
    // let fileIterator = rootInfo.scanFile(filter);
    if (!fileIterator) {
      console.error("scanFile interface returns an undefined object");
      return;
    }
    while (!isDone) {
      let result = fileIterator.next();
A
Annie_wang 已提交
446
      console.log("next result = " + JSON.stringify(result));
A
Annie_wang 已提交
447 448 449 450 451
      isDone = result.done;
      if (!isDone)
        subfileInfos.push(result.value);
    }
  } catch (error) {
A
Annie_wang 已提交
452
    console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
  }
  ```

## FileAccessHelper.createFile

createFile(uri: string, displayName: string) : Promise<string>

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 已提交
468 469 470
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | uri | string | Yes| URI of the parent directory for the file to create.|
A
Annie_wang 已提交
471
  | 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 已提交
472 473 474 475 476

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
477
| Promise<string> | Promise used to return the URI of the file created.|
A
Annie_wang 已提交
478 479 480 481

**Example**

  ```js
A
Annie_wang 已提交
482 483 484 485
  // 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 已提交
486 487 488
  let displayName = "file1"
  let fileUri = null;
  try {
A
Annie_wang 已提交
489
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
490 491 492 493 494
    fileUri = await fileAccessHelper.createFile(sourceUri, displayName)
    if (!fileUri) {
      console.error("createFile return undefined object");
      return;
    }
A
Annie_wang 已提交
495
    console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri));
A
Annie_wang 已提交
496
  } catch (error) {
A
Annie_wang 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

## FileAccessHelper.createFile

createFile(uri: string, displayName: string, callback: AsyncCallback<string>) : void;

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**

  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | uri | string | Yes| URI of the parent directory for the file to create.|
  | displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
  | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file created.|

**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 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
  };
  ```

## FileAccessHelper.mkDir

mkDir(parentUri: string, displayName: string) : Promise<string>

Creates a folder 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 已提交
553 554 555 556
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | parentUri | string | Yes| URI of the parent directory for the folder to create.|
  | displayName | string | Yes| Name of the folder to create.|
A
Annie_wang 已提交
557 558 559 560 561

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
562
| Promise<string> | Promise used to return the URI of the folder created.|
A
Annie_wang 已提交
563 564 565 566

**Example**

  ```js
A
Annie_wang 已提交
567 568 569 570
  // 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 已提交
571 572 573
  let dirName = "dirTest"
  let dirUri = null;
  try {
A
Annie_wang 已提交
574
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
575 576 577 578 579
    dirUri = await fileAccessHelper.mkDir(sourceUri, dirName)
    if (!dirUri) {
      console.error("mkDir return undefined object");
      return;
    }
A
Annie_wang 已提交
580
    console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri));
A
Annie_wang 已提交
581
  } catch (error) {
A
Annie_wang 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
    console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

## FileAccessHelper.mkDir

mkDir(parentUri: string, displayName: string, callback: AsyncCallback<string>) : void;

Creates a folder 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**

  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | parentUri | string | Yes| URI of the parent directory for the folder to create.|
  | displayName | string | Yes| Name of the folder to create.|
  | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the folder created.|

**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 已提交
623 624 625 626 627
  };
  ```

## FileAccessHelper.openFile

A
Annie_wang 已提交
628
openFile(uri: string, flags: OPENFLAGS) : Promise<number>
A
Annie_wang 已提交
629 630 631 632 633 634 635 636 637

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 已提交
638 639 640 641
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | uri | string | Yes| URI of the file to open.|
  | flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
A
Annie_wang 已提交
642 643 644 645 646

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
647
| Promise<number> | Promise used to return the handle to the file opened.|
A
Annie_wang 已提交
648 649 650 651

**Example**

  ```js
A
Annie_wang 已提交
652 653 654 655
  // The media library URI is used as an example.
  //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let targetUri  = "datashare:///media/file/100";
A
Annie_wang 已提交
656
  try {
A
Annie_wang 已提交
657 658 659
    // 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 已提交
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

## FileAccessHelper.openFile

openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback<number>) : void;

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**

  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | uri | string | Yes| URI of the file to open.|
  | flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
  | callback | AsyncCallback<number> | Yes| Promise used to return the handle to the file opened.|

**Example**

  ```js
  // The media library URI is used as an example.
  //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
  // 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 已提交
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
  };
  ```

## FileAccessHelper.delete

delete(uri: string) : Promise<number>

Deletes a file or folder. 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 已提交
715 716 717
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | uri | string | Yes| URI of the file or folder to delete.|
A
Annie_wang 已提交
718 719 720 721 722 723 724 725 726 727

**Return value**

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

**Example**

  ```js
A
Annie_wang 已提交
728 729 730 731
  // The media library URI is used as an example.
  //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let targetUri = "datashare:///media/file/100";
A
Annie_wang 已提交
732
  try {
A
Annie_wang 已提交
733
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
734 735 736
    let code = await fileAccessHelper.delete(targetUri);
    if (code != 0)
      console.error("delete failed, code " + code);
A
Annie_wang 已提交
737
  } catch (error) {
A
Annie_wang 已提交
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
    console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

## FileAccessHelper.delete

delete(uri: string, callback: AsyncCallback<number>) : void;

Deletes a file or folder. 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 file or folder to delete.|
  | callback | AsyncCallback<number> | Yes| Promise used to return the result.|

**Example**

  ```js
  // The media library URI is used as an example.
  //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
  // 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 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
  };
  ```

## FileAccessHelper.move

move(sourceFile: string, destFile: string) : Promise<string>

Moves a file or folder. 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 已提交
792 793 794 795
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | sourceFile | string | Yes| URI of the file or folder to move.|
  | destFile | string | Yes| URI of the folder to which the file or folder will be moved.|
A
Annie_wang 已提交
796 797 798 799 800

**Return value**

| Type| Description|
| ----- | ------ |
A
Annie_wang 已提交
801
| Promise<string> | Promise used to return the URI of the file or folder in the destination directory.|
A
Annie_wang 已提交
802 803 804 805

**Example**

  ```js
A
Annie_wang 已提交
806 807 808 809 810
  // The media library URI is used as an example.
  //In the sample code, sourceFile destFile indicates the file or folder in the Download directory. The URI is the URI in fileInfo.
  // You can use the URI obtained.
  let sourceFile = "datashare:///media/file/102";
  let destFile = "datashare:///media/file/101";
A
Annie_wang 已提交
811
  try {
A
Annie_wang 已提交
812
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
813
    let fileUri = await fileAccessHelper.move(sourceFile, destFile);
A
Annie_wang 已提交
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
    console.log("move sucess, fileUri: " + JSON.stringify(fileUri));
  } catch (error) {
    console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

## FileAccessHelper.move

move(sourceFile: string, destFile: string, callback: AsyncCallback<string>) : void;

Moves a file or folder. 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|
  | --- | --- | --- | -- |
  | sourceFile | string | Yes| URI of the file or folder to move.|
  | destFile | string | Yes| URI of the folder to which the file or folder will be moved.|
  | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file or folder in the destination directory.|

**Example**

  ```js
  // The media library URI is used as an example.
  //In the sample code, sourceFile destFile indicates the file or folder in the Download directory. The URI is the 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.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 已提交
855
  } catch (error) {
A
Annie_wang 已提交
856
    console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message);
A
Annie_wang 已提交
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
  };
  ```

## FileAccessHelper.rename

rename(uri: string, displayName: string) : Promise<string>

Renames a file or folder. 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 已提交
872 873 874 875
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | uri | string | Yes| URI of the file or folder to rename.|
  | displayName | string | Yes| New name of the file or folder, which can contain the file name extension.|
A
Annie_wang 已提交
876 877 878 879 880

**Return value**

| Type| Description|
| --- | -- |
A
Annie_wang 已提交
881
| Promise<string> | Promise used to return the URI of the renamed file or folder.|
A
Annie_wang 已提交
882 883 884 885

**Example**

  ```js
A
Annie_wang 已提交
886 887 888 889
  // 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 已提交
890
  try {
A
Annie_wang 已提交
891
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
892
    let DestDir = await fileAccessHelper.rename(sourceDir, "testDir");
A
Annie_wang 已提交
893
    console.log("rename sucess, DestDir: " + JSON.stringify(DestDir));
A
Annie_wang 已提交
894
  } catch (error) {
A
Annie_wang 已提交
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

## FileAccessHelper.rename

rename(uri: string, displayName: string, callback: AsyncCallback<string>) : void;

Renames a file or folder. 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 file or folder to rename.|
  | displayName | string | Yes| New name of the file or folder, which can contain the file name extension.|
  | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the renamed file or folder.|

**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 已提交
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
  };
  ```

## FileAccessHelper.access

access(sourceFileUri: string) : Promise<boolean>

Checks whether a file or folder exists. 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 已提交
950 951 952
  | Name| Type| Mandatory| Description|
  | --- | --- | --- | -- |
  | sourceFileUri | string | Yes| URI of the file or folder.|
A
Annie_wang 已提交
953 954 955 956 957 958 959 960 961 962

**Return value**

| Type| Description|
| --- | -- |
| Promise<boolean> | Promise used to return the result.|

**Example**

  ```js
A
Annie_wang 已提交
963 964 965 966
  // 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 已提交
967
  try {
A
Annie_wang 已提交
968
    // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
A
Annie_wang 已提交
969 970 971 972 973
    let existJudgment = await fileAccessHelper.access(sourceDir);
    if (existJudgment)
      console.log("sourceDir exists");
    else
      console.log("sourceDir does not exist");
A
Annie_wang 已提交
974
  } catch (error) {
A
Annie_wang 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message);
  };
  ```

## FileAccessHelper.access

access(sourceFileUri: string, callback: AsyncCallback<boolean>) : void;

Checks whether a file or folder exists. 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|
  | --- | --- | --- | -- |
  | sourceFileUri | string | Yes| URI of the file or folder.|
  | callback | AsyncCallback<boolean> | Yes| Promise used to return the result.|

**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 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
  };
  ```

## RootIterator.next

next( ) : { value: RootInfo, done: boolean }

Obtains the next-level device root directory. **RootIterator** is an iterator object of the device root directory.

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

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

**Return value**

| Type| Description|
| --- | -- |
| {value: RootInfo, done: boolean} | Root directory information obtained. This API traverses the folder until **done** returns **true**. The **value** field contains the root directory information.|

## FileIterator.next

next( ) : { value: FileInfo, done: boolean }

Obtains the information about the next-level file or folder. **FileIterator** is an iterator object of a folder.

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

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

**Return value**

| Type| Description|
| --- | -- |
| {value: FileInfo, done: boolean} | File or folder information obtained. This API traverses the specified folder until **done** returns **true**. The **value** field contains the file or folder information obtained.|

## RootInfo

Represents the root attribute information and interface capabilities of a device.

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

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

### Attributes

| Name| Type  | Readable| Writable| Description    |
| ------ | ------ | -------- | ------ | -------- |
| deviceType | number | Yes| No|Device type.|
| uri | string | Yes| No| Root directory URI of the device.|
| displayName | string | Yes| No| Device name.|
| deviceFlags | number | Yes| No| Capabilities supported by the device.|

## FileInfo

Represents the file or folder attribute information and interface capabilities.

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

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

### Attributes

| Name| Type  | Readable| Writable| Description    |
| ------ | ------ | -------- | ------ | -------- |
| uri | string | Yes| No| URI of the file or folder.|
| fileName | string | Yes| No| Name of a file or folder.|
| mode | number | Yes| No| Permissions on the file or folder.|
| size | number | Yes| No|  Size of the file or folder.|
| mtime | number | Yes| No|  Time when the file or folder was last modified.|
A
Annie_wang 已提交
1086
| mimeType | string | Yes| No|  MIME type of the file or folder.|
A
Annie_wang 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098

## OPENFLAGS

Enumerates the modes for opening a file.

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

| Name| Value| Description|
| ----- | ------ | ------ |
| READ | 0o0 | Read mode.|
| WRITE | 0o1 | Write mode.|
| WRITE_READ | 0o2 | Read/Write mode.|