1# File Path Management 2 3User data on OpenHarmony is managed by the **mediaLibrary** module in a unified manner. You can use the APIs provided by this module to access and operate the user data. 4 5> **NOTE** 6> 7> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**. 8 9To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md). 10 11## File Formats Supported by Public Directories 12 13Before using file paths for development, learn the file formats supported by each public directory. 14> **CAUTION** 15> 16> The following table lists only the file types that can be identified by the system. In your application development, pay attention to the file formats supported by the corresponding interfaces. <br> For example, only .jpeg and .webp can be used for image encoding, and only .jpg, .png, .gif, .bmp, .webp, and .raw can be used for image decoding. 17 18| Directory | Directory Type | Media Type | Description | Supported File Format | 19| ---------- | ------------- | ------------- | -------------- | ------------------------------------------------------------ | 20| Camera/ | DIR_CAMERA | VIDEO and IMAGE | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv | 21| Videos/ | DIR_VIDEO | VIDEO | Dedicated video directory. Only videos can be stored in this directory and its subdirectories.| .mp4 / .3gp / .mpg / .mov / .webm / .mkv | 22| Pictures/ | DIR_IMAGE | IMAGE | Dedicated image directory. Only images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif | 23| Audios/ | DIR_AUDIO | AUDIO |Dedicated audio directory. Only audio files can be stored in this directory and its subdirectories.| .aac/.mp3/.flac/.wav/.ogg | 24| Documents/ | DIR_DOCUMENTS | FILE |Dedicated file directory. Only files except audios, images, and videos can be stored in this directory and its subdirectories.| - | 25| Download/ | DIR_DOWNLOAD | ALLTYPE |Directory for storing downloaded files. The types of files in this directory and its subdirectories are not restricted.| - | 26 27## Obtaining a Public Directory 28 29Different types of files are stored in different public directories. You can call [getPublicDirectory](../reference/apis/js-apis-medialibrary.md#getpublicdirectory8-1) to obtain the public directory that stores files of a certain type. 30 31**Prerequisites** 32 33- You have obtained a **MediaLibrary** instance. 34- You have granted the permission **ohos.permission.READ_MEDIA**. 35 36The following describes how to obtain the public directory that stores camera files. 37 38```ts 39async function example(){ 40 const context = getContext(this); 41 let media = mediaLibrary.getMediaLibrary(context); 42 let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; 43 const dicResult = await media.getPublicDirectory(DIR_CAMERA); 44 if (dicResult == 'Camera/') { 45 console.info('mediaLibraryTest : getPublicDirectory passed'); 46 } else { 47 console.error('mediaLibraryTest : getPublicDirectory failed'); 48 } 49} 50``` 51 52## Copying Files Between the Application Sandbox and the Public Directory 53 54OpenHarmony provides the application sandbox to minimize the leakage of application data and user privacy information. 55 56Users can access files stored in the public directories through the system applications **Files** and **Gallery**. However, files in the application sandbox can be accessed only by the application itself. 57 58### Copying a File 59 60You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory. 61 62You can call [fs.open](../reference/apis/js-apis-file-fs.md#fsopen) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context. 63 64**Prerequisites** 65 66- You have obtained a **MediaLibrary** instance. 67- You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**. 68- You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary. 69- The **testFile.txt** file has been created and contains content. 70 71**How to Develop** 72 731. Call [context.filesDir](../reference/apis/js-apis-file-fs.md) to obtain the directory of the application sandbox. 742. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. 753. Call **fs.open** to open the file in the sandbox. 764. Call **fileAsset.open** to open the file in the public directory. 775. Call [fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile) to copy the file. 786. Call **fileAsset.close** and [fs.close](../reference/apis/js-apis-file-fs.md#fsclose) to close the file. 79 80**Example 1: Copying Files from the Public Directory to the Sandbox** 81 82```ts 83async function copyPublic2Sandbox() { 84 try { 85 const context = getContext(this); 86 let media = mediaLibrary.getMediaLibrary(context); 87 let sandboxDirPath = context.filesDir; 88 let fileKeyObj = mediaLibrary.FileKey; 89 let fileAssetFetchOp = { 90 selections: fileKeyObj.DISPLAY_NAME + '= ?', 91 selectionArgs: ['testFile.txt'], 92 }; 93 let fetchResult = await media.getFileAssets(fileAssetFetchOp); 94 let fileAsset = await fetchResult.getFirstObject(); 95 96 let fdPub = await fileAsset.open('rw'); 97 let fdSand = await fs.open(sandboxDirPath + '/testFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 98 await fs.copyFile(fdPub, fdSand.fd); 99 100 await fileAsset.close(fdPub); 101 await fs.close(fdSand.fd); 102 103 let content_sand = await fs.readText(sandboxDirPath + '/testFile.txt'); 104 console.info('content read from sandbox file: ', content_sand) 105 } catch (err) { 106 console.info('[demo] copyPublic2Sandbox fail, err: ', err); 107 } 108} 109``` 110 111**Example 2: Copying a File from the Sandbox to the Public Directory** 112 113```ts 114async function copySandbox2Public() { 115 const context = getContext(this); 116 let media = mediaLibrary.getMediaLibrary(context); 117 let sandboxDirPath = context.filesDir; 118 119 let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; 120 const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); 121 try { 122 let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); 123 console.info('createFile successfully, message = ' + fileAsset); 124 } catch (err) { 125 console.error('createFile failed, message = ' + err); 126 } 127 try { 128 let fileKeyObj = mediaLibrary.FileKey; 129 let fileAssetFetchOp = { 130 selections: fileKeyObj.DISPLAY_NAME + '= ?', 131 selectionArgs: ['testFile02.txt'], 132 }; 133 let fetchResult = await media.getFileAssets(fileAssetFetchOp); 134 var fileAsset = await fetchResult.getFirstObject(); 135 } catch (err) { 136 console.error('file asset get failed, message = ' + err); 137 } 138 let fdPub = await fileAsset.open('rw'); 139 let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', fs.OpenMode.READ_WRITE); 140 await fs.copyFile(fdSand.fd, fdPub); 141 await fileAsset.close(fdPub); 142 await fs.close(fdSand.fd); 143 let fdPubRead = await fileAsset.open('rw'); 144 try { 145 let arrayBuffer = new ArrayBuffer(4096); 146 await fs.read(fdPubRead, arrayBuffer); 147 var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); 148 fileAsset.close(fdPubRead); 149 } catch (err) { 150 console.error('read text failed, message = ', err); 151 } 152 console.info('content read from public file: ', content_pub); 153} 154``` 155 156### Reading and Writing a File 157 158You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fs.read** and **fs.write** in [file.fs](../reference/apis/js-apis-file-fs.md) to read and write the file. 159 160**Prerequisites** 161 162- You have obtained a **MediaLibrary** instance. 163- You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**. 164- You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary. 165 166**How to Develop** 167 1681. Create a file. 169 170```ts 171async function example() { 172 let mediaType = mediaLibrary.MediaType.FILE; 173 let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; 174 const context = getContext(this); 175 let media = mediaLibrary.getMediaLibrary(context); 176 const path = await media.getPublicDirectory(DIR_DOCUMENTS); 177 media.createAsset(mediaType, "testFile.txt", path).then((asset) => { 178 console.info("createAsset successfully:" + JSON.stringify(asset)); 179 }).catch((err) => { 180 console.error("createAsset failed with error: " + err); 181 }); 182} 183``` 184 1852. Call **FileAsset.open** to open the file. 186 1873. Call [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to write a string to the file. 188 1894. Call [fs.read](../reference/apis/js-apis-file-fs.md#fsread) to read the file and save the data read in an array buffer. 190 1915. Convert the array buffer to a string. 192 1936. Use **FileAsset.close** to close the file. 194 195**Example 1: Opening an Existing File and Writing Data to It** 196 197```ts 198async function writeOnlyPromise() { 199 const context = getContext(this); 200 let media = mediaLibrary.getMediaLibrary(context); 201 let fileKeyObj = mediaLibrary.FileKey; 202 let fileAssetFetchOp = { 203 selections: fileKeyObj.DISPLAY_NAME + '= ?', 204 selectionArgs: ['testFile.txt'], 205 }; 206 let fetchResult = await media.getFileAssets(fileAssetFetchOp); 207 let fileAsset = await fetchResult.getFirstObject(); 208 console.info('fileAssetName: ', fileAsset.displayName); 209 210 try { 211 let fd = await fileAsset.open('w'); 212 console.info('file descriptor: ', fd); 213 await fs.write(fd, "Write file test content."); 214 await fileAsset.close(fd); 215 } catch (err) { 216 console.error('write file failed, message = ', err); 217 } 218} 219``` 220 221**Example 2: Opening an Existing File and Reading Data from It** 222 223```ts 224async function readOnlyPromise() { 225 const context = getContext(this); 226 let media = mediaLibrary.getMediaLibrary(context); 227 let fileKeyObj = mediaLibrary.FileKey; 228 let fileAssetFetchOp = { 229 selections: fileKeyObj.DISPLAY_NAME + '= ?' , 230 selectionArgs: ['testFile.txt'], 231 }; 232 let fetchResult = await media.getFileAssets(fileAssetFetchOp); 233 let fileAsset = await fetchResult.getFirstObject(); 234 console.info('fileAssetName: ', fileAsset.displayName); 235 236 try { 237 let fd = await fileAsset.open('r'); 238 let arrayBuffer = new ArrayBuffer(4096); 239 await fs.read(fd, arrayBuffer); 240 let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); 241 globalThis.fileContent = fileContent; 242 globalThis.fileName = fileAsset.displayName; 243 console.info('file content: ', fileContent); 244 await fileAsset.close(fd); 245 } catch (err) { 246 console.error('read file failed, message = ', err); 247 } 248} 249``` 250