@@ -36,7 +36,7 @@ You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement ac
First, obtain the [application file path](../application-models/application-context-stage.md#obtaining-application-file-paths). The following example shows how to obtain a HAP file path using **UIAbilityContext**. For details about how to obtain **UIAbilityContext**, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
Then, perform common file operations.
Then, perform file operations.
### Creating, Reading, and Writing a File
...
...
@@ -46,21 +46,29 @@ The following example demonstrates how to create a file, read data from it, and
// After the applications to be restored are added, call getFileHandle() to obtain the handles of the application files to be restored based on the application name.
// The number of application data files to be restored varies depending on the number of backup files. The following is only an example.
awaitg_session.getFileHandle({
lethandle:backup.FileMeta={
bundleName:restoreApps[0],
uri:"manage.json"
});
awaitg_session.getFileHandle({
bundleName:restoreApps[0],
uri:"1.tar"
});
}
awaitg_session.getFileHandle(handle);
handle.uri="1.tar";
awaitg_session.getFileHandle(handle);
console.info('getFileHandle success');
}
```
...
...
@@ -249,23 +265,30 @@ If the application has not been installed, you can install the application and t
@@ -10,13 +10,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
| Module| API| Description|
| -------- | -------- | -------- |
| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.|
| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.|
| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.|
| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.|
| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.|
| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.|
**Table 2** Attributes for application space statistics
| BundleStats Attribute| Description| Directory for Statistics|
| BundleStats Attribute| Description| Directory for Statistics|
| -------- | -------- | -------- |
| appSize | Size of the application installation files, in bytes.| /data/storage/el1/bundle |
| cacheSize | Size of the application cache files, in bytes.| /data/storage/el1/base/cache<br>/data/storage/el1/base/haps/entry/cache<br>/data/storage/el2/base/cache<br>/data/storage/el2/base/haps/entry/cache |
...
...
@@ -25,12 +25,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
## Development Example
- Obtain the free space of **/data** of the file system.
@@ -8,82 +8,89 @@ For details about the APIs used to develop a file manager application, see [User
## How to Develop
1. Apply for permissions required.<br>
Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
1. Apply for permissions required.
Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
> **NOTE**
>
> **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs.
>
> **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
> - **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs.
>- **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development.
3. Query device information.<br>
3. Query device information.
You can obtain attributes of the devices managed by one or all file management servers in the system. You can also filter devices as required.
In the user file access framework, **RootInfo** indicates the attribute information of a device. For example, obtain **RootInfo** of all devices.
In the user file access framework, **FileInfo** indicates basic information about a file (directory). You can use **listfile()** to obtain a **FileIterator** object that traverses all files (directories) of the next level or use **scanfile()** to obtain a **FileIterator** object that meets the specified conditions.
Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse the next-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse the next-level files or filter the specified directories.
```ts
// Start from the root directory.
letrootInfo=rootinfos[0];
letfileInfos=[];
letisDone=false;
letfilter={suffix:[".txt",".jpg",".xlsx"]};// Set filter criteria.
try{
letfileIterator=rootInfo.listFile();// Traverse the root directory of rootinfos[0] and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object.
letrootInfo=rootInfos[0];
letfileInfos:Array<fileAccess.FileInfo>=[];
letisDone:boolean=false;
letfilter:Filter={suffix:[".txt",".jpg",".xlsx"]};// Set the filter.
try{
letfileIterator=rootInfo.listFile();// Traverse the root directory of rootinfos[0] and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object.
if(!fileIterator){
console.error("listFile interface returns an undefined object");
return;
}
while(!isDone){
letresult=fileIterator.next();
...
...
@@ -92,35 +99,37 @@ For details about the APIs used to develop a file manager application, see [User
You can integrate APIs of the user file access framework to implement user behaviors, such as deleting, renaming, creating, and moving a file (directory). The following example shows how to create a file. For details about other APIs, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md).
```ts
...
...
@@ -128,18 +137,20 @@ For details about the APIs used to develop a file manager application, see [User
// Create a file.
// sourceUri is the URI in fileinfo of the Download directory.
// You need to use the obtained URI for development.
letsourceUri="file://media/file/6";
letdisplayName="file1";
letfileUri=null;
try{
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
@@ -28,13 +28,13 @@ The following table describes the broadcast related parameters.
**Table 1** Broadcast parameters
| Broadcast| Parameter|
| Broadcast| Parameter|
| -------- | -------- |
| usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.|
| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.|
| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.<br>**fsUuid**: universally unique identifier (UUID) of the volume.<br>**path**: path where the volume is mounted.|
| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.|
| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.|
| usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.|
| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.|
| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.<br>**fsUuid**: universally unique identifier (UUID) of the volume.<br>**path**: path where the volume is mounted.|
| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.|
| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.|
## How to Develop
...
...
@@ -55,29 +55,33 @@ You can subscribe to broadcast events to observe the insertion and removal of ex
@@ -11,44 +11,48 @@ The **save()** method saves files in the file manager, not in **Gallery**.
For example, select an image from **Gallery** and save it to the file manager.
1. Import the [picker](../reference/apis/js-apis-file-picker.md), [fs](../reference/apis/js-apis-file-fs.md), [photoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md), and [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) modules.
1. Import the [picker](../reference/apis/js-apis-file-picker.md), [fs](../reference/apis/js-apis-file-fs.md), [photoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md), and [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) modules.
@@ -58,8 +62,8 @@ For example, select an image from **Gallery** and save it to the file manager.
The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
leturi:string;
asyncphotoViewPickerSave(){
leturis:Array<string>;
asyncfunctionphotoViewPickerSave(){
try{
constphotoSaveOptions=newpicker.PhotoSaveOptions();// Create a photoSaveOptions instance.
photoSaveOptions.newFileNames=["PhotoViewPicker01.png"];// (Optional) Name of the file to be saved. The file name in the square brackets can be customized and must be unique. If the file name already exists on the device, change the file name. Otherwise, an error will be returned.
...
...
@@ -68,15 +72,16 @@ For example, select an image from **Gallery** and save it to the file manager.
@@ -86,14 +91,15 @@ For example, select an image from **Gallery** and save it to the file manager.
Then, use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to modify the file based on the FD, and close the FD after the modification is complete.
@@ -105,6 +111,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
2. Create a **documentSaveOptions** instance.
...
...
@@ -112,6 +119,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
constdocumentSaveOptions=newpicker.DocumentSaveOptions();// Create a documentSaveOptions instance.
documentSaveOptions.newFileNames=["DocumentViewPicker01.txt"];// (Optional) Set the name of the document to save.
documentSaveOptions.fileSuffixChoices=['.png','.txt','.mp4'];// (Optional) Types of the documents to save.
```
3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the document. After the user selects the destination folder, the document is saved and the URI of the document saved is returned.
...
...
@@ -119,12 +127,12 @@ For example, select an image from **Gallery** and save it to the file manager.
The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
leturi=null;
leturis:Array<string>;
constdocumentViewPicker=newpicker.DocumentViewPicker();// Create a documentViewPicker instance.
console.info('documentViewPicker.save to file succeed and uris are:'+uris);
}).catch((err:BusinessError)=>{
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
...
...
@@ -151,6 +159,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
2. Create an **audioSaveOptions** instance.
...
...
@@ -160,17 +169,17 @@ For example, select an image from **Gallery** and save it to the file manager.
audioSaveOptions.newFileNames=['AudioViewPicker01.mp3'];// (Optional) Set the name of the audio file to save.
```
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the file. After the user selects the destination folder, the audio file is saved and the URI of the file saved is returned.
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the file. After the user selects the destination folder, the audio file is saved and the URI of the document saved is returned.
The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
@@ -17,6 +17,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
2. Create a **photoSelectOptions** instance.
...
...
@@ -38,12 +39,12 @@ The **FilePicker** provides the following interfaces by file type:
The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
documentSelectOptions.maxSelectNumber=5;// (Optional) Maximum number of documents to select.
documentSelectOptions.defaultFilePathUri="file://docs/storage/Users/currentUser/test";// (Optional) Path of the file or directory to select.
documentSelectOptions.fileSuffixFilters=['.png','.txt','.mp4'];// (Optional) File name extensions of the documents to select.
```
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents. After the documents are selected, a result set containing the file URIs is returned.
...
...
@@ -85,17 +91,13 @@ The **FilePicker** provides the following interfaces by file type:
For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attributes, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
leturi=null;
leturis:Array<string>;
constdocumentViewPicker=newpicker.DocumentViewPicker();// Create a documentViewPicker instance.
// Obtain the application sandbox path of the file.
...
...
@@ -43,6 +43,7 @@ Before sharing application files, you need to [obtain the application file path]
```
2. Set the target application, with which you want to share the file, and grant permissions on the file.
Use [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to share the file with the target application. You need to pass in the obtained URI in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis/js-apis-app-ability-want.md#attributes).
> **NOTE**
...
...
@@ -51,37 +52,39 @@ Before sharing application files, you need to [obtain the application file path]
console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
});
}
// ...
}
```
## Using Shared Files
In the [**module.json5** file](../quick-start/module-configuration-file.md) of the application, which wants to use the shared file, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by another application and set **uris** to the type of the URI to receive. In the following example, the application receives only .txt files with **scheme** of **file**.
...
...
@@ -120,10 +123,12 @@ After obtaining the URI of the shared file from **want**, the application can ca
```ts
// xxx.ets
importfsfrom'@ohos.file.fs';
importWantfrom'@ohos.app.ability.Want';
import{BusinessError}from'@ohos.base';
functiongetShareFile(){
try{
letwant=...;// Obtain the want information sent from the application that shares the file.
letwant:Want=...;// Obtain the want sent from the application that shares the file.
// Obtain the uri field from the want information.
leturi=want.uri;
...
...
@@ -135,11 +140,13 @@ function getShareFile() {
// Perform operations on the URI of the shared file as required. For example, open the URI to obtain the file object in read/write mode.
letfile=fs.openSync(uri,fs.OpenMode.READ_WRITE);
console.info('open file successfully!');
}catch(error){
}catch(err){
leterror:BusinessError=errasBusinessError;
console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`);
}
}catch(error){
console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`);
leterr:BusinessError=errorasBusinessError;
console.error(`Invoke openSync failed, code is ${err.code}, message is ${err.message}`);