0、代码

import fs from '@ohos.file.fs';
import { Logger } from './Logger';
import { Constants } from '../constants/Constants';
import { toast } from './ToastUtils';

export class FileUtils {

  /**
   * 获取目录下所有文件
   * @param filesDir
   * @returns
   */
  static getFiles(filesDir: string) {
    return this.getFilesWithFilter(filesDir);
  }

  /**
   * 获取目录下所有过滤的文件
   * @param filesDir
   * @returns
   */
  static async getFilesWithFilter(pathDir: string, filter?: any) {
    let files: string[]
    let options = {}
    if (filter !== undefined) {
      options = filter;
    }
    await fs.listFile(pathDir, options).then((filenames) => {
      files = filenames;
    }).catch((err) => {
      toast(err);
      files = [];
      Logger.error(Constants.TAG, JSON.stringify(err));
    });
    return files;
  }

  /**
   * 获取文件详细属性信息
   * @param filePath
   */
  static async getFileStat(filePath: string) {
    let resp;
    await  fs.stat(filePath).then((stat) => {
      resp = stat;
    }).catch((err) => {
      toast(err);
      Logger.error(Constants.TAG, JSON.stringify(err));
    });
    return resp;
  }

  /**
   * 检查文件是否存在
   * @param filePath
   */
  static async accessFile(filePath: string) {
    let resp = false;
    await  fs.access(filePath).then((res) => {
      resp = res;
    }).catch((err) => {
      toast(err);
      Logger.error(Constants.TAG, JSON.stringify(err));
    });
    return resp;
  }

  /**
   * 复制文件
   * @param filePath
   */
  static async copyFile(srcPath: string, dstPath: string) {
    let access = await this.accessFile(srcPath);
    if (access) {
      await fs.copyFile(srcPath, dstPath).then(() => {
        toast("复制成功");
        Logger.debug(Constants.TAG, "复制成功");
      }).catch((err) => {
        toast(err.message);
        Logger.error(Constants.TAG, "copy file failed with error message: " + err.message + ", error code: " + err.code);
      });
    } else {
      toast("原文件不存在!")
    }
  }

  /**
   * 创建目录
   * @param filePath
   */
  static async mkdir(dirPath: string) {
    await fs.mkdir(dirPath).then(() => {
      toast("创建成功");
      Logger.debug(Constants.TAG, "创建成功");
    }).catch((err) => {
      toast(err.message);
      Logger.error(Constants.TAG, "mkdir failed with error message: " + err.message + ", error code: " + err.code);
    });
  }

  /**
   * 打开文件读取数据
   * @param filePath
   */
  static async openAndRedFile(filePath: string) {
    let resp: string;
    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
    let buf = new ArrayBuffer(4096);
    await fs.read(file.fd, buf).then((readLen) => {
      Logger.debug(Constants.TAG, String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
      resp = String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)));
      fs.closeSync(file);
    }).catch((err) => {
      resp = "";
      Logger.error(Constants.TAG, "read file data failed with error message: " + err.message + ", error code: " + err.code);
    });
    return resp;
  }

  /**
   * 删除整个目录
   * @param filePath
   */
  static async rmdir(pathDir : string) {
    let access = await this.accessFile(pathDir);
    if (access) {
    await fs.rmdir(pathDir).then(() => {
      toast("删除成功");
      Logger.debug(Constants.TAG, "删除成功");
    }).catch((err) => {
      toast(err.message);
      Logger.error(Constants.TAG, "rmdir failed with error message: " + err.message + ", error code: " + err.code);
    });
    } else {
      toast("原文件不存在!")
    }
  }
}

1、使用:

static async test(){
    let filePath = getContext(this).filesDir;

    let files = await FileUtils.getFiles(filePath); // 列出文件夹下所有文件名

    let options = {
      "recursion": false, // 是否递归子目录下文件名,默认为false。
      "listNum": 0, // 列出文件名数量。当设置0时,列出所有文件,默认为0。
      "filter": {
        "suffix": [".png", ".jpg", ".jpeg", ".txt"], // Array<string>:文件后缀名完全匹配
        "displayName": ["*abc", "test2*"], // Array<string>:文件名模糊匹配
        //"mimeType": ["text/html"],                   // Array<string>:mime类型完全匹配
        "fileSizeOver": 0, // number:文件大小匹配
        "lastModifiedAfter": 0, // number:文件最近修改时间匹配,在指定时间点及之后的文件。
        "excludeMedia": false, // boolean:是否排除Media中已有的文件。
      }
    };
    let files2 = await FileUtils.getFilesWithFilter(filePath, options) // 列出文件夹下所有文件名,支持递归列出所有文件名(包含子目录下),支持文件过滤

    let stat = await FileUtils.getFileStat(filePath + "/test1.txt") //  获取文件详细属性信息
    Logger.debug(Constants.TAG, "ino:" + stat.ino) // 标识该文件。通常同设备上的不同文件的INO不同。
    Logger.debug(Constants.TAG, "mode:" + stat.mode) // 表示文件权限,各特征位的含义见:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V2/js-apis-file-fs-0000001451843016-V2#ZH-CN_TOPIC_0000001574088233__stat
    Logger.debug(Constants.TAG, "uid:" + stat.uid) // 文件所有者的ID。
    Logger.debug(Constants.TAG, "gid:" + stat.gid) // 文件所有组的ID。
    Logger.debug(Constants.TAG, "size:" + stat.size) // 文件的大小,以字节为单位。仅对普通文件有效。
    Logger.debug(Constants.TAG, "atime:" + stat.atime) // 上次访问该文件的时间,表示距1970年1月1日0时0分0秒的秒数。
    Logger.debug(Constants.TAG, "mtime:" + stat.mtime) // 上次修改该文件的时间,表示距1970年1月1日0时0分0秒的秒数。
    Logger.debug(Constants.TAG, "ctime:" + stat.ctime) // 最近改变文件状态的时间,表示距1970年1月1日0时0分0秒的秒数。

    let access = await FileUtils.accessFile(filePath + "/test1.txt") // 检查文件是否存在

    await FileUtils.copyFile(filePath + "/test1.txt", filePath + "/test22.txt") // 复制文件

    await FileUtils.mkdir(filePath + "/testDir")  // 创建目录

    let readLen = await  FileUtils.openAndRedFile(filePath + "/test1.txt")  // 打开.txt文件并读取内容

    await FileUtils.rmdir(filePath + "/testDir")  //  删除整个目录
  }

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐