• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Rawfile开发指导
2
3## 场景介绍
4
5开发者可以通过本指导了解在OpenHarmony应用中,如何使用Native Rawfile接口操作Rawfile目录和文件。功能包括文件列表遍历、文件打开、搜索、读取和关闭Rawfile。
6
7## 接口说明
8
9| 接口名                                                       | 描述                                     |
10| :----------------------------------------------------------- | :--------------------------------------- |
11| NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr) | 初始化native resource manager。          |
12| RawDir *OH_ResourceManager_OpenRawDir(const NativeResourceManager *mgr, const char *dirName) | 打开指定rawfile目录。                    |
13| int OH_ResourceManager_GetRawFileCount(RawDir *rawDir)       | 获取指定rawfile目录下的rawfile文件数量。 |
14| const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | 获取rawfile名字。                        |
15| RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | 打开指定rawfile文件。                    |
16| long OH_ResourceManager_GetRawFileSize(RawFile *rawFile)     | 获取rawfile文件大小。                    |
17| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | 指定rawfile内偏移量。                    |
18| long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | 获取rawfile偏移量。                      |
19| int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | 读取rawfile文件内容。                    |
20| void OH_ResourceManager_CloseRawFile(RawFile *rawFile)       | 释放rawfile文件相关资源。                |
21| void OH_ResourceManager_CloseRawDir(RawDir *rawDir)          | 释放rawfile目录相关资源。                |
22| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | 获取rawfile的fd。                        |
23| bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | 释放rawfile的fd。                        |
24| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | 释放native resource manager相关资源。    |
25
26## 函数介绍
27
281. 根据NativeResourceManager实例,使用OH_ResourceManager_OpenRawDir接口获取RawDir实例。
29
30    ```c++
31    RawDir* rawDir = OH_ResourceManager_OpenRawDir(nativeResourceManager, path.c_str());
32    ```
33
342. 根据RawDir实例,使用OH_ResourceManager_GetRawFileCount接口获取对应目录下的rawfile文件总数 。
35
36    ```c++
37    int count = OH_ResourceManager_GetRawFileCount(rawDir);
38    ```
39
403. 根据RawDir实例,使用OH_ResourceManager_GetRawFileName接口获取目录下对应index的rawfile文件名。
41
42    ```c++
43    for (int index = 0; index < count; index++) {
44        std::string fileName = OH_ResourceManager_GetRawFileName(rawDir, index);
45    }
46    ```
47
484. 根据NativeResourceManager实例,使用OH_ResourceManager_OpenRawFile接口获取指定文件名的RawFile实例
49
50    ```c++
51    RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str());
52    ```
53
545. 根据RawFile实例,使用OH_ResourceManager_GetRawFileSize接口获取对应rawfile文件大小。
55
56    ```c++
57    long rawFileSize = OH_ResourceManager_GetRawFileSize(rawFile);
58    ```
59
606. 根据RawFile实例,使用OH_ResourceManager_SeekRawFile接口指定rawfile偏移量。
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. 根据RawFile实例,使用OH_ResourceManager_GetRawFileOffset接口获取rawfile偏移量。
69
70    ```c++
71    long rawFileOffset = OH_ResourceManager_GetRawFileOffset(rawFile)
72    ```
73
748. 根据RawFile实例,使用OH_ResourceManager_ReadRawFile接口读取rawfile文件内容。
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. 根据RawFile实例,使用OH_ResourceManager_CloseRawFile接口释放rawfile文件相关资源。
82
83    ```c++
84    OH_ResourceManager_CloseRawFile(rawFile);
85    ```
86
8710. 根据RawDir实例,使用OH_ResourceManager_CloseRawDir接口释放rawfile目录相关资源。
88
89    ```c++
90    OH_ResourceManager_CloseRawDir(rawDir);
91    ```
92
9311. 根据RawFile实例,使用OH_ResourceManager_GetRawFileDescriptor接口获取rawfile的RawFileDescriptor。
94
95    ```c++
96    RawFileDescriptor descriptor;
97    bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);
98    ```
99
10012. 根据RawFileDescriptor实例,使用OH_ResourceManager_ReleaseRawFileDescriptor接口关闭rawfile的fd。
101
102    ```c++
103    OH_ResourceManager_ReleaseRawFileDescriptor(descriptor);
104    ```
105
10613. 根据NativeResourceManager实例,使用OH_ResourceManager_ReleaseNativeResourceManager接口释放native resource manager。
107
108    ```c++
109    OH_ResourceManager_ReleaseNativeResourceManager(nativeResourceManager);
110    ```
111
112## 开发步骤
113
114   以Js侧获取rawfile文件列表、rawfile文件内容、rawfile描述符{fd, offset, length}三种调用方式为例。
115
116**1. 创建工程**
117
118![创建C++应用](figures/rawfile1.png)
119
120**2. 添加依赖**
121
122创建完成后,IDE会在工程生成cpp目录,目录有libentry/index.d.tshello.cppCMakeLists.txt等文件。
123
1241. 打开src/main/cpp/CMakeLists.txt,在target_link_libraries依赖中添加资源的librawfile.z.so以及日志依赖libhilog_ndk.z.so
125
126    ```c++
127    target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so librawfile.z.so)
128    ```
129
1302. 打开src/main/cpp/types/libentry/index.d.ts文件,此文件声明了应用侧函数getFileList、getRawFileContent、getRawFileDescriptor。
131
132    ```c++
133    import resourceManager from '@ohos.resourceManager';
134    export const getFileList: (resmgr: resourceManager.ResourceManager, path: string) => Array<String>;
135    export const getRawFileContent: (resmgr: resourceManager.ResourceManager, path: string) => Uint8Array;
136    export const getRawFileDescriptor: (resmgr: resourceManager.ResourceManager, path: string) => resourceManager.RawFileDescriptor;
137    ```
138
139**3. 修改源文件**
140
1411. 打开src/main/cpp/hello.cpp文件,文件Init会对当前方法进行初始化映射,这里定义对外接口为getFileList、getRawFileContent、getRawFileDescriptor,映射C++接口分别为GetFileList、GetRawFileContent、GetRawFileDescriptor。
142
143    ```c++
144    EXTERN_C_START
145    static napi_value Init(napi_env env, napi_value exports)
146    {
147        napi_property_descriptor desc[] = {
148            { "getFileList", nullptr, GetFileList, nullptr, nullptr, nullptr, napi_default, nullptr },
149            { "getRawFileContent", nullptr, GetRawFileContent, nullptr, nullptr, nullptr, napi_default, nullptr },
150            { "getRawFileDescriptor", nullptr, GetRawFileDescriptor, nullptr, nullptr, nullptr, napi_default, nullptr }
151        };
152
153        napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
154        return exports;
155    }
156    EXTERN_C_END
157    ```
158
1592. 把src/main/cpp/hello.cpp文件中,增加对应的三个方法,如下所示
160
161    ```c++
162    static napi_value GetFileList(napi_env env, napi_callback_info info)
163    static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
164    static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info)
165    ```
166
1673. 在hello.cpp文件中获取Js的资源对象,并转为Native的资源对象,即可调用资源的Native接口,获取rawfile列表、rawfile文件内容以及rawfile描述符{fd, offset, length}三种调用方式示例代码如下:
168
169    ```c++
170    // 示例一:获取rawfile文件列表 GetFileList
171    static napi_value GetFileList(napi_env env, napi_callback_info info)
172    {
173        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest Begin");
174        size_t requireArgc = 3;
175        size_t argc = 2;
176        napi_value argv[2] = { nullptr };
177        // 获取参数信息
178        napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
179
180        // argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。
181        NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
182
183        // 获取函数argv[1],此为为rawfile相对路径
184        size_t strSize;
185        char strBuf[256];
186        napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
187        std::string dirName(strBuf, strSize);
188
189        // 获取对应的rawDir指针对象
190        RawDir* rawDir = OH_ResourceManager_OpenRawDir(mNativeResMgr, dirName.c_str());
191
192        // 获取rawDir下文件及文件夹数量
193        int count = OH_ResourceManager_GetRawFileCount(rawDir);
194
195        // 遍历获取文件名称,并保存
196        std::vector<std::string> tempArray;
197        for(int i = 0; i < count; i++) {
198            std::string filename = OH_ResourceManager_GetRawFileName(rawDir, i);
199            tempArray.emplace_back(filename);
200        }
201
202        napi_value fileList;
203        napi_create_array(env, &fileList);
204        for (size_t i = 0; i < tempArray.size(); i++) {
205            napi_value jsString;
206            napi_create_string_utf8(env, tempArray[i].c_str(), NAPI_AUTO_LENGTH, &jsString);
207            napi_set_element(env, fileList, i, jsString);
208        }
209
210        // 关闭打开的指针对象
211        OH_ResourceManager_CloseRawDir(rawDir);
212        OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
213        return fileList;
214    }
215
216    // 示例二:获取rawfile文件内容 GetRawFileContent
217    napi_value CreateJsArrayValue(napi_env env, std::unique_ptr<uint8_t[]> &data, long length)
218    {
219        napi_value buffer;
220        napi_status status = napi_create_external_arraybuffer(env, data.get(), length,
221                [](napi_env env, void *data, void *hint) {
222                    delete[] static_cast<char*>(data);
223                }, nullptr, &buffer);
224        if (status != napi_ok) {
225            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create external array buffer");
226            return nullptr;
227        }
228        napi_value result = nullptr;
229        status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result);
230        if (status != napi_ok) {
231            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create media typed array");
232            return nullptr;
233        }
234        data.release();
235        return result;
236    }
237    static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
238    {
239        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "GetFileContent Begin");
240        size_t requireArgc = 3;
241        size_t argc = 2;
242        napi_value argv[2] = { nullptr };
243        // 获取参数信息
244        napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
245
246        // argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。
247        NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
248        size_t strSize;
249        char strBuf[256];
250        napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
251        std::string filename(strBuf, strSize);
252
253        // 获取rawfile指针对象
254        RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str());
255        if (rawFile != nullptr) {
256            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success");
257        }
258        // 获取rawfile大小并申请内存
259        long len = OH_ResourceManager_GetRawFileSize(rawFile);
260        std::unique_ptr<uint8_t[]> data= std::make_unique<uint8_t[]>(len);
261        // 读取rawfile
262        int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len);
263        // 关闭打开的指针对象
264        OH_ResourceManager_CloseRawFile(rawFile);
265        OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
266        // 转为js对象
267        return CreateJsArrayValue(env, data, len);
268    }
269
270    // 示例三:获取rawfile文件描述符 GetRawFileDescriptor
271    napi_value createJsFileDescriptor(napi_env env, RawFileDescriptor &descriptor)
272    {
273        napi_value result;
274        napi_status status = napi_create_object(env, &result);
275        if (status != napi_ok) {
276            return result;
277        }
278
279        napi_value fd;
280        status = napi_create_int32(env, descriptor.fd, &fd);
281        if (status != napi_ok) {
282            return result;
283        }
284        status = napi_set_named_property(env, result, "fd", fd);
285        if (status != napi_ok) {
286            return result;
287        }
288
289        napi_value offset;
290        status = napi_create_int64(env, descriptor.start, &offset);
291        if (status != napi_ok) {
292            return result;
293        }
294        status = napi_set_named_property(env, result, "offset", offset);
295        if (status != napi_ok) {
296            return result;
297        }
298
299        napi_value length;
300        status = napi_create_int64(env, descriptor.length, &length);
301        if (status != napi_ok) {
302            return result;
303        }
304        status = napi_set_named_property(env, result, "length", length);
305        if (status != napi_ok) {
306            return result;
307        }
308        return result;
309    }
310    static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info)
311    {
312        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest GetRawFileDescriptor Begin");
313        size_t requireArgc = 3;
314        size_t argc = 2;
315        napi_value argv[2] = { nullptr };
316        // 获取参数信息
317        napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
318
319        napi_valuetype valueType;
320        napi_typeof(env, argv[0], &valueType);
321        // 获取native的resourceManager对象
322        NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
323        size_t strSize;
324        char strBuf[256];
325        napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
326        std::string filename(strBuf, strSize);
327        // 获取rawfile指针对象
328        RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str());
329        if (rawFile != nullptr) {
330            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success");
331        }
332        // 获取rawfile的描述符RawFileDescriptor {fd, offset, length}
333        RawFileDescriptor descriptor;
334        OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);
335        // 关闭打开的指针对象
336        OH_ResourceManager_CloseRawFile(rawFile);
337        OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
338        // 转为js对象
339        return createJsFileDescriptor(env,descriptor);
340    }
341    ```
342
343**4. Js侧调用**
344
3451. 打开src\main\ets\pages\index.ets, 导入"libentry.so";
346
3472. 获取当前js的resourceManager对象;
348
3493. 调用Native接口getFileList即为src/main/cpp/types/libentry/index.d.ts中声明的接口,传入js的资源对象,以及rawfile文件夹的相对路径。示例如下:
350
351    ```js
352    import hilog from '@ohos.hilog';
353    import testNapi from 'libentry.so'  // 导入so
354    @Entry
355    @Component
356    struct Index {
357        @State message: string = 'Hello World'
358        private resmgr = getContext().resourceManager;  // 获取js的资源对象
359        build() {
360            Row() {
361            Column() {
362                Text(this.message)
363                .fontSize(50)
364                .fontWeight(FontWeight.Bold)
365                .onClick(() => {
366                    hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
367                    let rawfilelist = testNapi.getFileList(this.resmgr, ""); //传入资源对象,以及访问的rawfile文件夹名称
368                    console.log("rawfilelist" + rawfilelist);
369                    let rawfileContet = testNapi.getRawFileContent(this.resmgr, "rawfile1.txt");
370                    console.log("rawfileContet" + rawfileContet);
371                    let rawfileDescriptor = testNapi.getRawFileDescriptor(this.resmgr, "rawfile1.txt");
372                    console.log("getRawFileDescriptor" + rawfileDescriptor.fd, rawfileDescriptor.offset, rawfileDescriptor.length);
373                })
374            }
375            .width('100%')
376            }
377            .height('100%')
378        }
379    }
380    ```
381
382## 相关实例
383
384针对资源管理Rawfile开发,有以下相关实例可供参考:
385
386- [获取Rawfile资源(API9)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-4.0-Release/code/BasicFeature/Native/NdkRawfile)
387