• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# RawFile Development
2
3## When to Use
4
5This document describes how to use Native Rawfile APIs to manage the directories and files in the **rawfile** directory in OpenHarmony. You can use the APIs to perform operations, such as traversing a directory and opening, searching for, reading, and closing a file in the the **rawfile** directory.
6
7## Available APIs
8
9| API                                                          | Description                                                  |
10| :----------------------------------------------------------- | :----------------------------------------------------------- |
11| NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr) | Initializes a Native resource manager instance.              |
12| RawDir *OH_ResourceManager_OpenRawDir(const NativeResourceManager *mgr, const char *dirName) | Opens a directory in the **rawfile** directory.              |
13| int OH_ResourceManager_GetRawFileCount(RawDir *rawDir)       | Obtains the number of files in the specified directory.      |
14| const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a file in the **rawfile** directory.     |
15| RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a file in the **rawfile** directory.                   |
16| long OH_ResourceManager_GetRawFileSize(RawFile *rawFile)     | Obtains the size of a file in the **rawfile** directory.     |
17| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks for the read/write position in a file in the **rawfile** directory based on the specified offset. |
18| long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset of a file.                                |
19| int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads data from a file in the **rawfile** directory.         |
20| void OH_ResourceManager_CloseRawFile(RawFile *rawFile)       | Closes a file in the **rawfile** directory to release resources. |
21| void OH_ResourceManager_CloseRawDir(RawDir *rawDir)          | Closes a directory in the **rawfile** directory to release resources. |
22| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a file in the **rawfile** directory. |
23| bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a file in the **rawfile** directory.      |
24| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases a Native resource manager instance.                 |
25
26## Functions
27
281. Call **OH_ResourceManager_OpenRawDir** to obtain a **RawDir** instance based on the **NativeResourceManager** instance.
29
30    ```c++
31    RawDir* rawDir = OH_ResourceManager_OpenRawDir(nativeResourceManager, path.c_str());
32    ```
33
342. Call **OH_ResourceManager_GetRawFileCount** to obtain the total number of files in the directory based on the **RawDir** instance.
35
36    ```c++
37    int count = OH_ResourceManager_GetRawFileCount(rawDir);
38    ```
39
403. Call **OH_ResourceManager_GetRawFileName** to obtain the name of a file based on the specified index.
41
42    ```c++
43    for (int index = 0; index < count; index++) {
44        std::string fileName = OH_ResourceManager_GetRawFileName(rawDir, index);
45    }
46    ```
47
484. Call **OH_ResourceManager_OpenRawFile** to open a **RawFile** instance with the specified file name.
49
50    ```c++
51    RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str());
52    ```
53
545. Call **OH_ResourceManager_GetRawFileSize** to obtain the size of the file.
55
56    ```c++
57    long rawFileSize = OH_ResourceManager_GetRawFileSize(rawFile);
58    ```
59
606. Call **OH_ResourceManager_SeekRawFile** to seek for the read/write position in the file based on the specified offset.
61
62    ```c++
63    int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0);
64    int position = OH_ResourceManager_SeekRawFile(rawFile, 0 , 1);
65    int position = OH_ResourceManager_SeekRawFile(rawFile, -10, 2);
66    ```
67
687. Call **OH_ResourceManager_GetRawFileOffset** to obtain the file offset.
69
70    ```c++
71    long rawFileOffset = OH_ResourceManager_GetRawFileOffset(rawFile)
72    ```
73
748. Call **OH_ResourceManager_ReadRawFile** to read a file.
75
76    ```c++
77    std::unique_ptr<char[]> mediaData = std::make_unique<char[]>(rawFileSize);
78    long rawFileOffset = OH_ResourceManager_ReadRawFile(rawFile, mediaData.get(), rawFileSize);
79    ```
80
819. Call **OH_ResourceManager_CloseRawFile** to close the file to release resources.
82
83    ```c++
84    OH_ResourceManager_CloseRawFile(rawFile);
85    ```
86
8710. Call **OH_ResourceManager_CloseRawDir** to close the file directory.
88
89    ```c++
90    OH_ResourceManager_CloseRawDir(rawDir);
91    ```
92
9311. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the file.
94
95    ```c++
96    RawFileDescriptor descriptor;
97    bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);
98    ```
99
10012. Call **OH_ResourceManager_ReleaseRawFileDescriptor** to release the FD of the file.
101
102    ```c++
103    OH_ResourceManager_ReleaseRawFileDescriptor(descriptor);
104    ```
105
10613. Call **OH_ResourceManager_ReleaseNativeResourceManager** to release the Native resource manager.
107
108    ```c++
109    OH_ResourceManager_ReleaseNativeResourceManager(nativeResourceManager);
110    ```
111
112## How to Develop
113
114The following describes how to obtain the file list in the **rawfile** directory, file content, and FD {fd, offset, length} on the JavaScript side as an example.
115
1161. Create a project.
117
118   ![Creating a C++ application](figures/rawfile1.png)
119
1202. Add dependencies.
121
122   After the project is created, the **cpp** directory is created under the project. The directory contains files such as **libentry/index.d.ts**, **hello.cpp**, and **CMakeLists.txt**.
123
124   1. Open the **src/main/cpp/CMakeLists.txt** file, and add **librawfile.z.so** and **libhilog_ndk.z.so** to **target_link_libraries**.
125
126      ```
127      target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so librawfile.z.so)
128      ```
129
130
131
132   2. Open the **src/main/cpp/types/libentry/index.d.ts** file, and declare the application functions **getFileList**, **getRawFileContent**, and **getRawFileDescriptor**.
133
134      ```c++
135      import resourceManager from '@ohos.resourceManager';
136      export const getFileList: (resmgr: resourceManager.ResourceManager, path: string) => Array<String>;
137      export const getRawFileContent: (resmgr: resourceManager.ResourceManager, path: string) => Uint8Array;
138      export const getRawFileDescriptor: (resmgr: resourceManager.ResourceManager, path: string) => resourceManager.RawFileDescriptor;
139      ```
140
141
142
1433. Modify the source file.
144
145   1. Open the **src/main/cpp/hello.cpp** file. During initialization, the file maps the external JavaScript APIs **getFileList**, **getRawFileContent**, and **getRawFileDescriptor** to C++ native APIs **GetFileList**, **GetRawFileContent**, and **GetRawFileDescriptor**.
146
147      ```c++
148      EXTERN_C_START
149      static napi_value Init(napi_env env, napi_value exports)
150      {
151          napi_property_descriptor desc[] = {
152              { "getFileList", nullptr, GetFileList, nullptr, nullptr, nullptr, napi_default, nullptr },
153              { "getRawFileContent", nullptr, GetRawFileContent, nullptr, nullptr, nullptr, napi_default, nullptr },
154              { "getRawFileDescriptor", nullptr, GetRawFileDescriptor, nullptr, nullptr, nullptr, napi_default, nullptr }
155          };
156
157          napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
158          return exports;
159      }
160      EXTERN_C_END
161      ```
162
163
164
165   2. Add the three functions to the **src/main/cpp/hello.cpp** file.
166
167      ```c++
168      static napi_value GetFileList(napi_env env, napi_callback_info info)
169      static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
170      static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info)
171      ```
172
173
174
175   3. Obtain JavaScript resource objects from the **hello.cpp** file, and convert them to Native resource objects. Then, call the Native APIs to obtain the file list, file content, and FD {fd, offset, length}.
176
177      The sample code is as follows:
178
179      ```c++
180      // Example 1: Use GetFileList to obtain the raw file list.
181      static napi_value GetFileList(napi_env env, napi_callback_info info)
182      {
183          OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest Begin");
184          size_t requireArgc = 3;
185          size_t argc = 2;
186          napi_value argv[2] = { nullptr };
187          // Obtain arguments of the native API.
188          napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
189
190          // Obtain argv[0], which specifies conversion of the JavaScript resource object (that is, OH_ResourceManager_InitNativeResourceManager) to a native object.
191          NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
192
193          // Obtain argv[1], which specifies the relative path of the raw file.
194          size_t strSize;
195          char strBuf[256];
196          napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
197          std::string dirName(strBuf, strSize);
198
199          // Obtain the corresponding rawDir pointer object.
200          RawDir* rawDir = OH_ResourceManager_OpenRawDir(mNativeResMgr, dirName.c_str());
201
202          // Obtain the number of files and folders in rawDir.
203          int count = OH_ResourceManager_GetRawFileCount(rawDir);
204
205          // Traverse rawDir to obtain the list of file names and save it.
206          std::vector<std::string> tempArray;
207          for(int i = 0; i < count; i++) {
208              std::string filename = OH_ResourceManager_GetRawFileName(rawDir, i);
209              tempArray.emplace_back(filename);
210          }
211
212          napi_value fileList;
213          napi_create_array(env, &fileList);
214          for (size_t i = 0; i < tempArray.size(); i++) {
215              napi_value jsString;
216              napi_create_string_utf8(env, tempArray[i].c_str(), NAPI_AUTO_LENGTH, &jsString);
217              napi_set_element(env, fileList, i, jsString);
218          }
219
220          // Close the rawDir pointer object.
221          OH_ResourceManager_CloseRawDir(rawDir);
222          OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
223          return fileList;
224      }
225
226      // Example 2: Use rawDir pointer object to obtain the content of the raw file.
227      napi_value CreateJsArrayValue(napi_env env, std::unique_ptr<uint8_t[]> &data, long length)
228      {
229          napi_value buffer;
230          napi_status status = napi_create_external_arraybuffer(env, data.get(), length,
231                  [](napi_env env, void *data, void *hint) {
232                      delete[] static_cast<char*>(data);
233                  }, nullptr, &buffer);
234          if (status != napi_ok) {
235              OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create external array buffer");
236              return nullptr;
237          }
238          napi_value result = nullptr;
239          status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result);
240          if (status != napi_ok) {
241              OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create media typed array");
242              return nullptr;
243          }
244          data.release();
245          return result;
246      }
247      static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
248      {
249          OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "GetFileContent Begin");
250          size_t requireArgc = 3;
251          size_t argc = 2;
252          napi_value argv[2] = { nullptr };
253          // Obtain arguments of the native API.
254          napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
255
256          // Obtain argv[0], which specifies conversion of the JavaScript resource object (that is, OH_ResourceManager_InitNativeResourceManager) to a native object.
257          NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
258          size_t strSize;
259          char strBuf[256];
260          napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
261          std::string filename(strBuf, strSize);
262
263          // Obtain the raw file pointer object.
264          RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str());
265          if (rawFile != nullptr) {
266              OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success");
267          }
268          // Obtain the size of the raw file and apply for memory.
269          long len = OH_ResourceManager_GetRawFileSize(rawFile);
270          std::unique_ptr<uint8_t[]> data= std::make_unique<uint8_t[]>(len);
271          // Read the raw file.
272          int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len);
273          // Close the rawDir pointer object.
274          OH_ResourceManager_CloseRawFile(rawFile);
275          OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
276          // Convert the native object to a JavaScript object.
277          return CreateJsArrayValue(env, data, len);
278      }
279
280      // Example 3: Use GetRawFileDescriptor to obtain the FD of the raw file.
281      napi_value createJsFileDescriptor(napi_env env, RawFileDescriptor &descriptor)
282      {
283          napi_value result;
284          napi_status status = napi_create_object(env, &result);
285          if (status != napi_ok) {
286              return result;
287          }
288
289          napi_value fd;
290          status = napi_create_int32(env, descriptor.fd, &fd);
291          if (status != napi_ok) {
292              return result;
293          }
294          status = napi_set_named_property(env, result, "fd", fd);
295          if (status != napi_ok) {
296              return result;
297          }
298
299          napi_value offset;
300          status = napi_create_int64(env, descriptor.start, &offset);
301          if (status != napi_ok) {
302              return result;
303          }
304          status = napi_set_named_property(env, result, "offset", offset);
305          if (status != napi_ok) {
306              return result;
307          }
308
309          napi_value length;
310          status = napi_create_int64(env, descriptor.length, &length);
311          if (status != napi_ok) {
312              return result;
313          }
314          status = napi_set_named_property(env, result, "length", length);
315          if (status != napi_ok) {
316              return result;
317          }
318          return result;
319      }
320      static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info)
321      {
322          OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest GetRawFileDescriptor Begin");
323          size_t requireArgc = 3;
324          size_t argc = 2;
325          napi_value argv[2] = { nullptr };
326          // Obtain arguments of the native API.
327          napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
328
329          napi_valuetype valueType;
330          napi_typeof(env, argv[0], &valueType);
331          // Obtain the native resourceManager object.
332          NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
333          size_t strSize;
334          char strBuf[256];
335          napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
336          std::string filename(strBuf, strSize);
337          // Obtain the raw file pointer object.
338          RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str());
339          if (rawFile != nullptr) {
340              OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success");
341          }
342          // Obtain the FD of the raw file, that is, RawFileDescriptor {fd, offset, length}.
343          RawFileDescriptor descriptor;
344          OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);
345          // Close the rawDir pointer object.
346          OH_ResourceManager_CloseRawFile(rawFile);
347          OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
348          // Convert the native object to a JavaScript object.
349          return createJsFileDescriptor(env,descriptor);
350      }
351      ```
352
353
354
3554. Call JavaScript APIs.
356
357   1. Open **src\main\ets\pages\index.ets**, and import **libentry.so**.
358
359   2. Obtain the JavaScript resource object, that is, **resourceManager**.
360
361   3. Call **getFileList**, that is, the Native API declared in **src/main/cpp/types/libentry/index.d.ts**. When calling the API, pass in the JavaScript resource object and the relative path of the file.
362
363      The sample code is as follows:
364
365      ```js
366      import hilog from '@ohos.hilog';
367      import testNapi from 'libentry.so'  // Import the libentry.so file.
368      @Entry
369      @Component
370      struct Index {
371          @State message: string = 'Hello World'
372          private resmgr = getContext().resourceManager;  // Obtain the JavaScript resource object.
373          build() {
374              Row() {
375              Column() {
376                  Text(this.message)
377                  .fontSize(50)
378                  .fontWeight(FontWeight.Bold)
379                  .onClick(() => {
380                      hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
381                      let rawfilelist = testNapi.getFileList(this.resmgr, ""); // Pass the JavaScript resource object and the relative path of the raw file.
382                      console.log("rawfilelist" + rawfilelist);
383                      let rawfileContet = testNapi.getRawFileContent(this.resmgr, "rawfile1.txt");
384                      console.log("rawfileContet" + rawfileContet);
385                      let rawfileDescriptor = testNapi.getRawFileDescriptor(this.resmgr, "rawfile1.txt");
386                      console.log("getRawFileDescriptor" + rawfileDescriptor.fd, rawfileDescriptor.offset, rawfileDescriptor.length);
387                  })
388              }
389              .width('100%')
390              }
391              .height('100%')
392          }
393      }
394      ```
395
396
397
398