FileUtils.ets 1.43 KB

import fs from '@ohos.file.fs';
import { BusinessError } from '@kit.BasicServicesKit';
import { util } from '@kit.ArkTS';

export class FileUtils {

  // 文件是否存在,忽略错误
  static fileExsit(path: string) : Promise<boolean> {
    return new Promise((reslove, fail) => {
      fs.stat(path).then(() => {
        reslove(true)
      }).catch((error: BusinessError) => {
        if (error.code = 13900002) {
          reslove(false)
        } else {
          reslove(true)
        }
      })
    });
  }

  static makeDirIfNotExsit(path: string) : Promise<void> {
    return new Promise((reslove, fail) => {
      fs.stat(path).then(() => {
        reslove()
      }).catch((error: BusinessError) => {
        if (error.code = 13900002) {
          fs.mkdirSync(path)
        }
        reslove()
      })
    })
  }

  static readFile(path: string): ArrayBuffer {
    try {
      let stat = fs.statSync(path)
      let fd = fs.openSync(path, fs.OpenMode.READ_ONLY).fd;
      let length = stat.size
      let buf = new ArrayBuffer(length);
      fs.readSync(fd, buf)
      fs.closeSync(fd)
      return buf
    } catch (e) {
      console.log("FileUtils - readFilePicSync " + e)
      return new ArrayBuffer(0)
    }
  }

  static readFileAsString(path: string): string {
    const data = FileUtils.readFile(path)
    let decoder = util.TextDecoder.create('utf-8');
    let str = decoder.decodeToString(new Uint8Array(data));
    return str
  }
}