• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * Copyright (c) 2021-2022 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
16/**
17 * An util that provides io functionality between file and JSON object.
18 */
19import Fileio from '@ohos.fileio';
20import util from '@ohos.util';
21import { Log } from './Log';
22
23const TAG = 'FileUtils';
24
25const READ_DATA_SIZE = 4096;
26
27export default class FileUtils {
28
29  /**
30   * Read Json file from disk by file path.
31   *
32   * @param {string} filePath - filePath as the absolute path to the target file.
33   * @return {any} - read object from file
34   */
35  static readJsonFile(filePath: string): any {
36    Log.showDebug(TAG, 'readJsonFile start execution');
37    let readStreamSync = null;
38    try {
39      readStreamSync = Fileio.createStreamSync(filePath, 'r');
40      const content = this.getContent(readStreamSync);
41      return JSON.parse(content);
42    } catch (e) {
43      Log.showError(TAG, `readJsonFile error: ${e.toString()}`);
44    } finally {
45      readStreamSync.closeSync();
46    }
47  }
48
49  /**
50   * Read String from disk by bundleName.
51   *
52   * @param {string} filePath - filePath as the absolute path to the target file.
53   * @return {string} - read string from file
54   */
55  static readStringFromFile(filePath: string): string {
56    Log.showDebug(TAG, 'readStringFromFile start execution');
57    let readStreamSync = null;
58    try {
59      readStreamSync = Fileio.createStreamSync(filePath, 'r');
60      const content = this.getContent(readStreamSync);
61      return content;
62    } catch (e) {
63      Log.showError(TAG, `readStringFromFile error: ${e.toString()}, filePath: ${filePath}`);
64    } finally {
65      if (readStreamSync) {
66        readStreamSync.closeSync();
67      }
68    }
69  }
70
71  /**
72   * Write string to a file.
73   *
74   * @param {string} str - target string will be written to file.
75   * @param {string} filePath - filePath as the absolute path to the target file.
76   */
77  static writeStringToFile(str: string, filePath: string): void {
78    Log.showDebug(TAG, 'writeStringToFile start execution');
79    let writeStreamSync = null;
80    try {
81      writeStreamSync = Fileio.createStreamSync(filePath, 'w+');
82      let number = writeStreamSync.writeSync(str);
83      Log.showDebug(TAG, 'writeStringToFile number: ' + number);
84    } catch (e) {
85      Log.showError(TAG, `writeStringToFile error: ${e.toString()}`);
86    } finally {
87      writeStreamSync.closeSync();
88      Log.showDebug(TAG, 'writeStringToFile close sync');
89    }
90  }
91
92  /**
93   * Read JSON object from a file.
94   *
95   * @param {object} readStreamSync - stream of target file
96   * @return {object} - object read from file stream
97   */
98  static getContent(readStreamSync: any): string {
99    Log.showDebug(TAG, 'getContent start');
100    const bufArray = [];
101    let totalLength = 0;
102    let buf = new ArrayBuffer(READ_DATA_SIZE);
103    let len = readStreamSync.readSync(buf);
104    while (len != 0) {
105      Log.showDebug(TAG, `getContent FileIO reading ${len}`);
106      totalLength += len;
107      if (len < READ_DATA_SIZE) {
108        buf = buf.slice(0, len);
109        bufArray.push(buf);
110        break;
111      }
112      bufArray.push(buf);
113      buf = new ArrayBuffer(READ_DATA_SIZE);
114      len = readStreamSync.readSync(buf);
115    }
116    Log.showDebug(TAG, `getContent read finished: ${totalLength}`);
117    const contentBuf = new Uint8Array(totalLength);
118    let offset = 0;
119    for (const bufArr of bufArray) {
120      Log.showDebug(TAG, `getContent collecting: ${offset}`);
121      const uInt8Arr = new Uint8Array(bufArr);
122      contentBuf.set(uInt8Arr, offset);
123      offset += uInt8Arr.byteLength;
124    }
125    let textDecoder = new util.TextDecoder('utf-8', {ignoreBOM: true});
126    const content = textDecoder.decode(contentBuf, {stream: false});
127    return content;
128  }
129
130  /**
131   * Check if the file exists.
132   *
133   * @param {string} filePath - filePath as the absolute path to the target file.
134   * @return {boolean} - boolean true(Exist)
135   */
136  static isExist(filePath: string): boolean {
137    try {
138      Fileio.accessSync(filePath);
139      Log.showDebug(TAG, 'accessSync success.');
140    } catch(e) {
141      Log.showError(TAG, `isExit error: ${e.toString()}`);
142      return false;
143    }
144    return true;
145  }
146
147  /**
148   * Delete Files.
149   *
150   * @param {string} filePath - filePath as the absolute path to the target file.
151   */
152  static deleteConfigFile(filePath: string): void {
153    try {
154      Fileio.unlinkSync(filePath);
155    } catch(e) {
156      Log.showError(TAG, `deleteFile error: ${e.toString()}`);
157    }
158  }
159}