@@ -36,7 +36,7 @@ You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement ac
...
@@ -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).
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
### Creating, Reading, and Writing a File
...
@@ -46,21 +46,29 @@ The following example demonstrates how to create a file, read data from it, and
...
@@ -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.
// 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.
// 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],
bundleName:restoreApps[0],
uri:"manage.json"
uri:"manage.json"
});
}
awaitg_session.getFileHandle({
awaitg_session.getFileHandle(handle);
bundleName:restoreApps[0],
handle.uri="1.tar";
uri:"1.tar"
awaitg_session.getFileHandle(handle);
});
console.info('getFileHandle success');
console.info('getFileHandle success');
}
}
```
```
...
@@ -249,23 +265,30 @@ If the application has not been installed, you can install the application and t
...
@@ -249,23 +265,30 @@ If the application has not been installed, you can install the application and t
@@ -8,46 +8,52 @@ For details about the APIs used to develop a file manager application, see [User
...
@@ -8,46 +8,52 @@ For details about the APIs used to develop a file manager application, see [User
## How to Develop
## How to Develop
1. Apply for permissions required.<br>
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).
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**
> **NOTE**
>
>
> **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs.
> - **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.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.
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.
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, **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.
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.
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
```ts
// Start from the root directory.
// Start from the root directory.
letrootInfo=rootinfos[0];
letrootInfo=rootInfos[0];
letfileInfos=[];
letfileInfos:Array<fileAccess.FileInfo>=[];
letisDone=false;
letisDone:boolean=false;
letfilter={suffix:[".txt",".jpg",".xlsx"]};// Set filter criteria.
letfilter:Filter={suffix:[".txt",".jpg",".xlsx"]};// Set the filter.
try{
try{
letfileIterator=rootInfo.listFile();// Traverse the root directory of rootinfos[0] and return an iterator object.
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.
// let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object.
if(!fileIterator){
if(!fileIterator){
console.error("listFile interface returns an undefined object");
console.error("listFile interface returns an undefined object");
return;
}
}
while(!isDone){
while(!isDone){
letresult=fileIterator.next();
letresult=fileIterator.next();
...
@@ -92,35 +99,37 @@ For details about the APIs used to develop a file manager application, see [User
...
@@ -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).
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
```ts
...
@@ -128,18 +137,20 @@ For details about the APIs used to develop a file manager application, see [User
...
@@ -128,18 +137,20 @@ For details about the APIs used to develop a file manager application, see [User
// Create a file.
// Create a file.
// sourceUri is the URI in fileinfo of the Download directory.
// sourceUri is the URI in fileinfo of the Download directory.
// You need to use the obtained URI for development.
// You need to use the obtained URI for development.
@@ -11,44 +11,48 @@ The **save()** method saves files in the file manager, not in **Gallery**.
...
@@ -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.
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.
...
@@ -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.
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
```ts
leturi:string;
leturis:Array<string>;
asyncphotoViewPickerSave(){
asyncfunctionphotoViewPickerSave(){
try{
try{
constphotoSaveOptions=newpicker.PhotoSaveOptions();// Create a photoSaveOptions instance.
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.
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.
...
@@ -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.
...
@@ -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.
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.
...
@@ -105,6 +111,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
```ts
importpickerfrom'@ohos.file.picker';
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
```
2. Create a **documentSaveOptions** instance.
2. Create a **documentSaveOptions** instance.
...
@@ -112,6 +119,7 @@ For example, select an image from **Gallery** and save it to the file manager.
...
@@ -112,6 +119,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
```ts
constdocumentSaveOptions=newpicker.DocumentSaveOptions();// Create a documentSaveOptions instance.
constdocumentSaveOptions=newpicker.DocumentSaveOptions();// Create a documentSaveOptions instance.
documentSaveOptions.newFileNames=["DocumentViewPicker01.txt"];// (Optional) Set the name of the document to save.
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.
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.
...
@@ -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.
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
```ts
leturi=null;
leturis:Array<string>;
constdocumentViewPicker=newpicker.DocumentViewPicker();// Create a documentViewPicker instance.
constdocumentViewPicker=newpicker.DocumentViewPicker();// Create a documentViewPicker instance.
console.info('documentViewPicker.save to file succeed and uri is:'+uri);
console.info('documentViewPicker.save to file succeed and uris are:'+uris);
}).catch((err)=>{
}).catch((err:BusinessError)=>{
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
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.
...
@@ -151,6 +159,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
```ts
importpickerfrom'@ohos.file.picker';
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
```
2. Create an **audioSaveOptions** instance.
2. Create an **audioSaveOptions** instance.
...
@@ -160,17 +169,17 @@ For example, select an image from **Gallery** and save it to the file manager.
...
@@ -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.
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.
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:
...
@@ -17,6 +17,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts
```ts
importpickerfrom'@ohos.file.picker';
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
```
2. Create a **photoSelectOptions** instance.
2. Create a **photoSelectOptions** instance.
...
@@ -38,12 +39,12 @@ The **FilePicker** provides the following interfaces by file type:
...
@@ -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.
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.
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:
...
@@ -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).
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
```ts
leturi=null;
leturis:Array<string>;
constdocumentViewPicker=newpicker.DocumentViewPicker();// Create a documentViewPicker instance.
constdocumentViewPicker=newpicker.DocumentViewPicker();// Create a documentViewPicker instance.
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
}
}
```
```
4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
...
@@ -150,6 +155,7 @@ The **FilePicker** provides the following interfaces by file type:
...
@@ -150,6 +155,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts
```ts
importpickerfrom'@ohos.file.picker';
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
```
2. Create an **audioSelectOptions** instance.
2. Create an **audioSelectOptions** instance.
...
@@ -169,12 +175,12 @@ The **FilePicker** provides the following interfaces by file type:
...
@@ -169,12 +175,12 @@ The **FilePicker** provides the following interfaces by file type:
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing
...
@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing
The file URIs are in the following format:
The file URIs are in the following format:
**file**://<*bundleName*>/<*path*>
**file://**<bundleName>/<path>
-**file**: indicates a file URI.
-**file**: indicates a file URI.
...
@@ -43,6 +43,7 @@ Before sharing application files, you need to [obtain the application file path]
...
@@ -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.
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).
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**
> **NOTE**
...
@@ -54,6 +55,8 @@ Before sharing application files, you need to [obtain the application file path]
...
@@ -54,6 +55,8 @@ 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}`);
console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
});
});
}
}
// ...
...
}
}
```
```
## Using Shared Files
## 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**.
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
...
@@ -120,10 +123,12 @@ After obtaining the URI of the shared file from **want**, the application can ca
```ts
```ts
// xxx.ets
// xxx.ets
importfsfrom'@ohos.file.fs';
importfsfrom'@ohos.file.fs';
importWantfrom'@ohos.app.ability.Want';
import{BusinessError}from'@ohos.base';
functiongetShareFile(){
functiongetShareFile(){
try{
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.
// Obtain the uri field from the want information.
leturi=want.uri;
leturi=want.uri;
...
@@ -135,11 +140,13 @@ function getShareFile() {
...
@@ -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.
// 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);
letfile=fs.openSync(uri,fs.OpenMode.READ_WRITE);
console.info('open file successfully!');
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}`);
console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`);
}
}
}catch(error){
}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}`);