• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Raw File Development
2
3## When to Use
4
5This document describes how to use native RawFile APIs to manage raw file directories and files in OpenHarmony. You can use the APIs to perform operations such as traversing a file list and opening, searching for, reading, and closing raw files.
6The APIs ended with **64** are new APIs. These APIs can be used to open raw files larger than 2 GB. For details, see [Rawfile](../reference/apis-localization-kit/rawfile.md). The development procedure is the same for the API ended with **64** and the one does not. For example, you can use **OH_ResourceManager_OpenRawFile** and **OH_ResourceManager_OpenRawFile64** in the same way.
7
8## Available APIs
9
10| API                                                      | Description                                    |
11| :----------------------------------------------------------- | :--------------------------------------- |
12| NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr) | Initializes the native resource manager.         |
13| RawDir *OH_ResourceManager_OpenRawDir(const NativeResourceManager *mgr, const char *dirName) | Opens a raw file directory.                   |
14| int OH_ResourceManager_GetRawFileCount(RawDir *rawDir)       | Obtains the number of raw files in a directory.|
15| const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a raw file.                       |
16| RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a raw file.                   |
17| long OH_ResourceManager_GetRawFileSize(RawFile *rawFile)     | Obtains the size of a raw file.                   |
18| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a read/write position in a raw file based on the specified offset.                   |
19| long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset of a raw file.                     |
20| int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads a raw file.                   |
21| int64_t OH_ResourceManager_GetRawFileRemainingLength(const RawFile *rawFile) | Obtains the remaining length of a raw file.                   |
22| void OH_ResourceManager_CloseRawFile(RawFile *rawFile)       | Closes a raw file to release resources.               |
23| void OH_ResourceManager_CloseRawDir(RawDir *rawDir)          | Closes a raw file directory to release resources.               |
24| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a raw file.                       |
25| bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a raw file.                       |
26| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases the native resource manager.   |
27| bool OH_ResourceManager_IsRawDir(const NativeResourceManager *mgr, const char *path) | Checks whether a path is a subdirectory in the **rawfile** directory.   |
28
29For details about the APIs, see [Function Description](../reference/apis-localization-kit/rawfile.md#function-description).
30
31## How to Develop
32
33   The following describes how to obtain the raw file list, raw file content, and raw file descriptor(fd, offset, length) using ArkTS as an example.
34
351. Create a project on DevEco Studio.
36
37![Creating a C++ application](figures/rawfile1.png)
38
392. Add dependencies.
40
41After the project is created, the **cpp** directory is created in the project directory. In the **cpp** directory, there are files such as **libentry/index.d.ts**, **hello.cpp**, and **CMakeLists.txt**.
42
431. Open the **src/main/cpp/CMakeLists.txt** file, and add **librawfile.z.so** and **libhilog_ndk.z.so** to **target_link_libraries**.
44
45    ```c++
46    target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so librawfile.z.so)
47    ```
48
492. Open the **src/main/cpp/types/libentry/index.d.ts** file, and declare the application functions **getFileList**, **getRawFileContent**, and **getRawFileDescriptor**.
50
51    ```c++
52    import resourceManager from '@ohos.resourceManager';
53    export const getFileList: (resmgr: resourceManager.ResourceManager, path: string) => Array<String>;
54    export const getRawFileContent: (resmgr: resourceManager.ResourceManager, path: string) => Uint8Array;
55    export const getRawFileDescriptor: (resmgr: resourceManager.ResourceManager, path: string) => resourceManager.RawFileDescriptor;
56    export const isRawDir: (resmgr: resourceManager.ResourceManager, path: string) => Boolean;
57    ```
58
593. Modify the source file.
60
611. Open the **src/main/cpp/hello.cpp** file. During initialization, the file maps the external JavaScript (JS) APIs **getFileList**, **getRawFileContent**, and **getRawFileDescriptor** to C++ native APIs **GetFileList**, **GetRawFileContent**, and **GetRawFileDescriptor**.
62
63    ```c++
64    EXTERN_C_START
65    static napi_value Init(napi_env env, napi_value exports)
66    {
67        napi_property_descriptor desc[] = {
68            { "getFileList", nullptr, GetFileList, nullptr, nullptr, nullptr, napi_default, nullptr },
69            { "getRawFileContent", nullptr, GetRawFileContent, nullptr, nullptr, nullptr, napi_default, nullptr },
70            { "getRawFileDescriptor", nullptr, GetRawFileDescriptor, nullptr, nullptr, nullptr, napi_default, nullptr },
71            { "isRawDir", nullptr, IsRawDir, nullptr, nullptr, nullptr, napi_default, nullptr }
72        };
73
74        napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
75        return exports;
76    }
77    EXTERN_C_END
78    ```
79
802. Add the three C++ native APIs to the **src/main/cpp/hello.cpp** file.
81
82    ```c++
83    static napi_value GetFileList(napi_env env, napi_callback_info info)
84    static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
85    static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info)
86    static napi_value IsRawDir(napi_env env, napi_callback_info info)
87    ```
88
893. Obtain JS resource objects from the **hello.cpp** file, and convert them to native resource objects. Then, call the native APIs to obtain the raw file list, raw file content, and raw file descriptor (fd, offset, length). The sample code is as follows:
90
91    ```c++
92    #include <rawfile/raw_file.h>
93    #include <rawfile/raw_dir.h>
94    #include <rawfile/raw_file_manager.h>
95
96    // Example 1: Use GetFileList to obtain the raw file list.
97    static napi_value GetFileList(napi_env env, napi_callback_info info)
98    {
99        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest Begin");
100        size_t requireArgc = 3;
101        size_t argc = 2;
102        napi_value argv[2] = { nullptr };
103        // Obtain arguments of the native API.
104        napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
105
106        // argv[0] is the first parameter of the function, which is a JS resource object. The function OH_ResourceManager_InitNativeResourceManager converts this JS resource object into a native object.
107        NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
108
109        // Obtain argv[1], which specifies the relative path of the raw file.
110        size_t strSize;
111        char strBuf[256];
112        napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
113        std::string dirName(strBuf, strSize);
114
115        // Obtain the corresponding rawDir pointer object.
116        RawDir* rawDir = OH_ResourceManager_OpenRawDir(mNativeResMgr, dirName.c_str());
117
118        // Obtain the number of files and folders in rawDir.
119        int count = OH_ResourceManager_GetRawFileCount(rawDir);
120
121        // Traverse rawDir to obtain the list of file names and save it.
122        std::vector<std::string> tempArray;
123        for(int i = 0; i < count; i++) {
124            std::string filename = OH_ResourceManager_GetRawFileName(rawDir, i);
125            tempArray.emplace_back(filename);
126        }
127
128        napi_value fileList;
129        napi_create_array(env, &fileList);
130        for (size_t i = 0; i < tempArray.size(); i++) {
131            napi_value jsString;
132            napi_create_string_utf8(env, tempArray[i].c_str(), NAPI_AUTO_LENGTH, &jsString);
133            napi_set_element(env, fileList, i, jsString);
134        }
135
136        // Close the rawDir pointer object.
137        OH_ResourceManager_CloseRawDir(rawDir);
138        OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
139        return fileList;
140    }
141
142    // Example 2: Use GetRawFileContent to obtain the content of the raw file.
143    napi_value CreateJsArrayValue(napi_env env, std::unique_ptr<uint8_t[]> &data, long length)
144    {
145        napi_value buffer;
146        napi_status status = napi_create_external_arraybuffer(env, data.get(), length,
147                [](napi_env env, void *data, void *hint) {
148                    delete[] static_cast<char*>(data);
149                }, nullptr, &buffer);
150        if (status != napi_ok) {
151            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create external array buffer");
152            return nullptr;
153        }
154        napi_value result = nullptr;
155        status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result);
156        if (status != napi_ok) {
157            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create media typed array");
158            return nullptr;
159        }
160        data.release();
161        return result;
162    }
163    static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
164    {
165        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "GetFileContent Begin");
166        size_t requireArgc = 3;
167        size_t argc = 2;
168        napi_value argv[2] = { nullptr };
169        // Obtain arguments of the native API.
170        napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
171
172        // argv[0] is the first parameter of the function, which is a JS resource object. The function OH_ResourceManager_InitNativeResourceManager converts this JS resource object into a native object.
173        NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
174        size_t strSize;
175        char strBuf[256];
176        napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
177        std::string filename(strBuf, strSize);
178
179        // Obtain the raw file pointer object.
180        RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str());
181        if (rawFile != nullptr) {
182            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success");
183        }
184        // Obtain the size of the raw file and apply for memory.
185        long len = OH_ResourceManager_GetRawFileSize(rawFile);
186        std::unique_ptr<uint8_t[]> data= std::make_unique<uint8_t[]>(len);
187
188        // Read all content of the raw file at a time.
189        int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len);
190
191        // Read all content of the raw file by multiple times, with 100 bytes per time.
192        // long offset = 0;
193        // while (OH_ResourceManager_GetRawFileRemainingLength(rawFile) > 0) {
194        //     OH_ResourceManager_ReadRawFile(rawFile, data.get() + offset, 100);
195        //     offset += 100;
196        // }
197
198        // Close the rawDir pointer object.
199        OH_ResourceManager_CloseRawFile(rawFile);
200        OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
201        // Convert the native object to a JS object.
202        return CreateJsArrayValue(env, data, len);
203    }
204
205    // Example 3: Use GetRawFileDescriptor to obtain the FD of the raw file.
206    napi_value createJsFileDescriptor(napi_env env, RawFileDescriptor &descriptor)
207    {
208        napi_value result;
209        napi_status status = napi_create_object(env, &result);
210        if (status != napi_ok) {
211            return result;
212        }
213
214        napi_value fd;
215        status = napi_create_int32(env, descriptor.fd, &fd);
216        if (status != napi_ok) {
217            return result;
218        }
219        status = napi_set_named_property(env, result, "fd", fd);
220        if (status != napi_ok) {
221            return result;
222        }
223
224        napi_value offset;
225        status = napi_create_int64(env, descriptor.start, &offset);
226        if (status != napi_ok) {
227            return result;
228        }
229        status = napi_set_named_property(env, result, "offset", offset);
230        if (status != napi_ok) {
231            return result;
232        }
233
234        napi_value length;
235        status = napi_create_int64(env, descriptor.length, &length);
236        if (status != napi_ok) {
237            return result;
238        }
239        status = napi_set_named_property(env, result, "length", length);
240        if (status != napi_ok) {
241            return result;
242        }
243        return result;
244    }
245    static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info)
246    {
247        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest GetRawFileDescriptor Begin");
248        size_t requireArgc = 3;
249        size_t argc = 2;
250        napi_value argv[2] = { nullptr };
251        // Obtain arguments of the native API.
252        napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
253
254        napi_valuetype valueType;
255        napi_typeof(env, argv[0], &valueType);
256        // Obtain the native resource manager 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        // Obtain the raw file pointer object.
263        RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str());
264        if (rawFile != nullptr) {
265            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success");
266        }
267        // Obtain the FD of the raw file, that is, RawFileDescriptor (fd, offset, length).
268        RawFileDescriptor descriptor;
269        OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);
270        // Close the rawDir pointer object.
271        OH_ResourceManager_CloseRawFile(rawFile);
272        OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
273        // Convert the native object to a JS object.
274        return createJsFileDescriptor(env,descriptor);
275    }
276    napi_value CreateJsBool(napi_env env, bool &bValue)
277    {
278        napi_value jsValue = nullptr;
279        if (napi_get_boolean(env, bValue, &jsValue) != napi_ok) {
280            return nullptr;
281        }
282        return jsValue;
283    }
284    static napi_value IsRawDir(napi_env env, napi_callback_info info)
285    {
286        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest IsRawDir Begin");
287        size_t requireArgc = 3;
288        size_t argc = 2;
289        napi_value argv[2] = { nullptr };
290        // Obtain arguments of the native API.
291        napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
292
293        napi_valuetype valueType;
294        napi_typeof(env, argv[0], &valueType);
295        // Obtain the native resource manager.
296        NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
297
298        napi_valuetype valueType1;
299        napi_typeof(env, argv[1], &valueType);
300        if (valueType1 == napi_undefined || valueType1 == napi_null) {
301            bool temp = false;
302            return CreateJsBool(env, temp);
303        }
304        size_t strSize;
305        char strBuf[256];
306        napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
307        std::string filename(strBuf, strSize);
308        // Obtain the raw file pointer object.
309        bool result = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str());
310        OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
311        return CreateJsBool(env, result);
312    }
313    ```
314
3154. Call JS APIs.
316
3171. Open the **src\main\ets\pages\index.ets** file, and import **libentry.so**.
318
3192. Obtain intra-package resources and cross-package resources within an application and cross-application package resources.<br>Call **.context().resourceManager** to obtain a **resourceManager** object for intra-package resources within the application.<br>Call **.context().createModuleContext().resourceManager** to obtain a **resourceManager** object for cross-package resources within the application.<br>Call **.context.createModuleContext(bundleName: 'bundleName name', moduleName: 'module name').resourceManager** to obtain a **resourceManager** object for cross-application package resources. This API can be used only by system applications.<br>For details about **Context**, see [Context (Stage Model)](../application-models/application-context-stage.md).
320
3213. Call **getFileList**, that is, the native API declared in **src/main/cpp/types/libentry/index.d.ts**. When calling the API, pass in the JS resource object and the relative path of the raw file.
322
323   Example: Obtain a **resourceManager** object for intra-package resources within the application.
324
325    ```js
326    import hilog from '@ohos.hilog';
327    import testNapi from 'libentry.so'  // Import the libentry.so file.
328    @Entry
329    @Component
330    struct Index {
331        @State message: string = 'Hello World';
332        private resmgr = this.getUIContext().getHostContext()?.resourceManager;  // Obtain the resourceManager object for intra-package resources within the application.
333        build() {
334            Row() {
335            Column() {
336                Text(this.message)
337                .fontSize(50)
338                .fontWeight(FontWeight.Bold)
339                .onClick(() => {
340                    hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
341                    let rawfilelist = testNapi.getFileList(this.resmgr, ""); // Pass in the JS resource object and the relative path of the raw file.
342                    console.log("rawfilelist" + rawfilelist);
343                    let rawfileContent = testNapi.getRawFileContent(this.resmgr, "rawfile1.txt");
344                    console.log("rawfileContent" + rawfileContent);
345                    let rawfileDescriptor = testNapi.getRawFileDescriptor(this.resmgr, "rawfile1.txt");
346                    console.log("getRawFileDescriptor" + rawfileDescriptor.fd, rawfileDescriptor.offset, rawfileDescriptor.length);
347                    let ret = testNapi.isRawDir(this.resmgr, "rawfile1.txt");
348                })
349            }
350            .width('100%')
351            }
352            .height('100%')
353        }
354    }
355    ```
356
357##
358
359
360
361-
362