1/**
2 * Copyright (c) 2024-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import util from '@ohos.util';
17import resmgr from '@ohos.resourceManager';
18import Logger from './Logger';
19
20const TAG: string = 'RawFileUtil';
21const UNICODE: string = 'utf-8';
22
23/**
24 * RawFile utility class
25 */
26export class RawFileUtil {
27  /**
28   * Get the object of the specified JSON file
29   *
30   * @param resourceManager Resource Manager
31   * @param fileName file name
32   * @returns The file content in string format
33   */
34  public static async getStringByFile(resourceManager: resmgr.ResourceManager, fileName: string): Promise<string> {
35    Logger.info(TAG, `getFileContent. fileName: ${fileName}`);
36    if (resourceManager === null || fileName === null) {
37      Logger.error(TAG, `getFileContent failed.resourceManager or fileName is null.fileName:${fileName}`);
38      return '';
39    }
40    try {
41      let value: Uint8Array = await resourceManager.getRawFileContent(fileName);
42      let content = util.TextDecoder.create(UNICODE).decodeWithStream(value);
43      return content;
44    } catch (jsonError) {
45      Logger.error(TAG, `JSON parse error: ${jsonError?.code} ${jsonError?.message}`);
46    }
47    return '';
48  }
49
50  /**
51   * Get the object of the specified JSON file
52   *
53   * @param context context
54   * @param fileName file name
55   * @return The file content in string format
56   */
57  public static async getRawFileByContext(context: Context, fileName: string): Promise<string> {
58    Logger.info(TAG, `getFileContent. fileName: ${fileName}`);
59    if (context === null || fileName === null) {
60      Logger.error(TAG, `getFileContent failed.resourceManager or fileName is null.fileName:${fileName}`);
61      return '';
62    }
63    try {
64      let value: Uint8Array = await context.resourceManager.getRawFileContent(fileName);
65      let content = util.TextDecoder.create('utf-8').decodeWithStream(value);
66      return content;
67    } catch (jsonError) {
68      Logger.error(TAG, `JSON parse error: ${jsonError?.code} ${jsonError?.message}`);
69    }
70    return '';
71  }
72}