FileUtil.ets 2.3 KB
import fs from '@ohos.file.fs';
import buffer from '@ohos.buffer';


// 大小和单位
const GB_MAGNITUDE: number = 1024 * 1024 * 1024
const MB_MAGNITUDE: number = 1024 * 1024
const KB_MAGNITUDE: number = 1024
const GB_SYMBOL: string = 'GB'
const MB_SYMBOL: string = 'MB'
const KB_SYMBOL: string = 'KB'
const BYTE_SYMBOL: string = 'B'

export class FileUtil {


  /**
   * 新建并打开文件
   */
  static createOrOpen(path: string) : fs.File{
    let isExist = fs.accessSync(path);
    let file: fs.File;
    if(isExist) {
      file = fs.openSync(path, fs.OpenMode.READ_WRITE);
    }else {
      file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    }
    return file;
  }


  /**
   * 保存arrayBuffer到文件
   * @param path
   * @param arrayBuffer
   * @returns
   */
  static writeBufferToFile(path: string, arrayBuffer: ArrayBuffer): number {

    try {
      let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      let value = fs.writeSync(file.fd, arrayBuffer);
      fs.closeSync(file);
      return value;
    }catch (err){
      console.log("FileUtil", "writeFile err:" + err);
      return -1;
    }
  }


  /**
   * 保存文本到文件
   * @param path
   * @param text
   * @returns
   */
  static writeStrToFile(path: string, text: string): number {
    try {
      let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      let value = fs.writeSync(file.fd, text);
      fs.closeSync(file);
      return value;
    }catch (err) {
      console.log("FileUtil", "writeFile err:" + err);
      return -1;
    }
  }
}


export class CommonConstants {
  /**
   * ShowToast duration.
   */
  static readonly SHOW_TOAST_DURATION: number = 4000;

  /**
   * ShowToast bottom.
   */
  static readonly SHOW_TOAST_BOTTOM: number = 108;

  /**
   * Image size.
   */
  static readonly IMAGE_SIZE: number = 200;

  /**
   * The full percentage of component.
   */
  static readonly FULL_PERCENT: string = '100%';

  /**
   * The ninety percent of the components.
   */
  static readonly NINETY_PERCENT: string = '90%';

  /**
   * The seventy percent of the components.
   */
  static readonly SEVENTY_PERCENT: string = '70%';

  /**
   * The fifteen percent of the bottom of the margin.
   */
  static readonly FIFTEEN_PERCENT: string = '15%';
}