文件管理工具类(Harmony OS)

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

工具类源码,如下:

TypeScript 复制代码
import fs from '@ohos.file.fs'
import buffer from '@ohos.buffer'
/**
 * @auther:jsxin
 * email:[email protected]
 * 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','张三')
  }

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

相关推荐
lqj_本人6 小时前
鸿蒙OS&UniApp结合机器学习打造智能图像分类应用:HarmonyOS实践指南#三方框架 #Uniapp
机器学习·uni-app·harmonyos
哼唧唧_7 小时前
使用 React Native 开发鸿蒙运动健康类应用的高频易错点总结
react native·react.js·harmonyos·harmony os5·运动健康
二流小码农9 小时前
鸿蒙开发:loading动画的几种实现方式
android·ios·harmonyos
大胖子10110 小时前
HarmonyOS5ArkTS常见数据类型认识
harmonyos
大胖子10110 小时前
HarmonyOS5鸿蒙开发常用装饰器
harmonyos
大胖子10110 小时前
HarmonyOS5鸿蒙开发常用组件介绍
harmonyos
小镇梦想家11 小时前
鸿蒙NEXT-Flutter(1)
harmonyos
zhanshuo12 小时前
安卓→鸿蒙迁移实战:3步重构消息提示,解锁跨设备协同黑科技!
harmonyos
不爱吃糖的程序媛13 小时前
鸿蒙版Taro 搭建开发环境
华为·harmonyos·taro
zhanshuo14 小时前
鸿蒙实战:智能灯泡状态监控,低功耗预警方案揭秘!
harmonyos