文件管理工具类(Harmony OS)

前言:接上一篇preferences首选项存储后,整理的第二个文件管理工具类,目前项目中用到的功能有限,后续如有新增再继续更新,老规矩直接上代码。

工具类源码,如下:

TypeScript 复制代码
import fs from '@ohos.file.fs'
import buffer from '@ohos.buffer'
/**
 * @auther:jsxin
 * email:jsxin0816@163.com
 * date: 2024/8/12
 * desc: 文件管理工具类
 */
class FileManagerUtils {

  /**
   * 文件存储路径
   */
  private static path = '/FileStorage/'
  private context: Context
  static instance: FileManagerUtils

  static getInstance(context: Context) {
    if (!FileManagerUtils) {
      this.instance = new FileManagerUtils()
    }
    return this.instance
  }

  /**
   * 工具类初始化
   * @param context 上下文
   * desc: 推荐在EntryAbillity的onCreate方法中初始化
   */
  init(context: Context) {
    this.context = context
  }

  /**
   * 将数据保存到文件
   * @param fileName 文件名
   * @param data 文件数据源
   * @returns 存储结果:true or false
   */
  saveData(fileName: string, data: string): boolean {
    if (!this.context) {
      console.debug('FileManagerUtils--->>>[saveData] 未进行初始化:context为null')
    }
    if (!fileName || !data) {
      console.debug('FileManagerUtils--->>>[saveData] fileName或data未空')
    }
    //文件跟路径
    let rootDir = this.context.filesDir + FileManagerUtils.path

    try {
      //判断目录是否存在,如果不存在,则创建
      let isDirExists = fs.accessSync(rootDir)
      if (!isDirExists) {
        fs.mkdirSync(rootDir)
      }

      //文件路径
      let filePath = rootDir + fileName
      //数据写入
      let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC)
      fs.writeSync(file.fd, data)

      //文件关闭
      fs.close(file)
      return true
    } catch (err) {
      console.debug('FileManagerUtils--->>>[saveData]  err.code = ' + err.code + '  err.message = ' + err.message)
      return false
    }
  }

  /**
   * 获取文件数据
   * @param fileName 文件名称
   * @returns 文件数据
   */
  getData(fileName: string): string {
    if (!this.context) {
      console.debug('FileManagerUtils--->>>[getData] 未进行初始化:context为null')
    }
    if (!fileName) {
      console.debug('FileManagerUtils--->>>[getData] fileName未空')
    }
    //文件全路径
    let filePath = this.context.filesDir + FileManagerUtils.path + fileName

    //线判断文件是否存在
    let isFileExists = fs.accessSync(filePath)
    if (!isFileExists) {
      console.debug('FileManagerUtils--->>>[getData] 文件不存在')
      return ''
    }

    try {
      //读取文件
      let file = fs.openSync(filePath)
      let bufferSize = fs.statSync(file.fd).size
      let buf = new ArrayBuffer(bufferSize)
      fs.readSync(file.fd, buf, { offset: 0, length: bufferSize })
      let bufData = buffer.from(buf)
      let text = bufData.toString()

      //关闭文件
      fs.closeSync(file)
      return text
    } catch (err) {
      console.debug('FileManagerUtils--->>>[getData] 数据读取失败!err.code = ' + err.code + '  err.message = ' + err.message)
      return ''
    }
  }

  /**
   * 判断文件是否已存在
   * @param fileName 文件名称
   * @returns 结果:true or false
   */
   isFileExists (fileName: string): boolean {
    try {
      if (!fileName) {
        return false
      }
      //文件全路径
      let filePath = this.context.filesDir + FileManagerUtils.path + fileName
      return fs.accessSync(filePath)
    } catch (err) {
      console.debug('FileManagerUtils--->>>[isFileExists] err.code = ' + err.code + '  err.message = ' + err.message)
      return false
    }
  }

  /**
   * 删除文件
   * @param fileName 文件名称
   * @returns 删除结果:true or false
   */
  deleteFile (fileName: string): boolean {
    try {
      if (!fileName) {
        return false
      }
      //文件全路径
      let filePath = this.context.filesDir + FileManagerUtils.path + fileName
      //判断文件是否存在
      let isFileExists = fs.accessSync(filePath)
      if (isFileExists) {
        fs.unlinkSync(filePath)
      }
      return true
    } catch (err) {
      console.debug('FileManagerUtils--->>>[deleteFile] err.code = ' + err.code + '  err.message = ' + err.message)
      return false
    }
  }
}
const fileManagerUtils = new FileManagerUtils()
export default fileManagerUtils as FileManagerUtils

使用步骤:

1、初始化,如下:

TypeScript 复制代码
//1、引入工具类
import FileManagerUtils from '../utils/FileManagerUtils'

export default class EntryAbility extends UIAbility {
   onCreate(want, launchParam) {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');

     //2、FileManagerUtils初始化
     FileManagerUtils.init(this.context.getApplicationContext())
  }

2、在页面使用,如下:

TypeScript 复制代码
//1、引入工具包
import FileManagerUtils from '../utils/FileManagerUtils'

@Entry
@Component
struct Index {
  aboutToAppear(){

    //2、在需要的地方进行使用
    FileManagerUtils.saveData('name.txt','张三')
  }

如有问题或建议欢迎指正!

相关推荐
RZer3 小时前
Hypium+python鸿蒙原生自动化安装配置
python·自动化·harmonyos
ChinaDragonDreamer5 小时前
HarmonyOS:状态管理最佳实践
harmonyos·鸿蒙
行十万里人生5 小时前
Qt事件处理:理解处理器、过滤器与事件系统
开发语言·git·qt·华为od·华为·华为云·harmonyos
黄暄11 小时前
HarmonyOS DevEco Studio模拟器点击运行没有反应的解决方法
harmonyos
AnyaPapa11 小时前
HarmonyOS简介:高效开发与测试
华为·harmonyos
御承扬12 小时前
从零开始开发纯血鸿蒙应用之自定义构建函数
华为·harmonyos
ChinaDragonDreamer12 小时前
HarmonyOS:ForEach:循环渲染
harmonyos·鸿蒙
taopi202421 小时前
鸿蒙开发在onPageShow中数据加载不完整的问题分析与解决
harmonyos
枫叶丹43 天前
【HarmonyOS之旅】基于ArkTS开发(三) -> 兼容JS的类Web开发(三)
开发语言·前端·javascript·华为·harmonyos
AnyaPapa5 天前
HarmonyOS简介:HarmonyOS核心技术理念
华为·harmonyos