文件管理工具类(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','张三')
  }

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

相关推荐
轻口味2 分钟前
【每日学点HarmonyOS Next知识】Web交互、列表拖拽、横屏后布局、Event序列问题、Scroll与Web组合
前端·交互·harmonyos·harmonyosnext
轻口味10 小时前
【每日学点HarmonyOS Next知识】截图组件截取列表、Toggle组件、Web组件请求头、列表选择弹窗、游戏加速
前端·游戏·harmonyos·harmonyosnext
鸿蒙开发工程师—阿辉10 小时前
HarmonyOS Next元服务网络请求封装实践
网络·华为·typescript·harmonyos·元服务
__Benco14 小时前
OpenHarmony 5.0.0 Release
harmonyos
别说我什么都不会15 小时前
鸿蒙轻内核M核源码分析系列二一 03 文件系统LittleFS
操作系统·嵌入式·harmonyos
全栈若城16 小时前
04 高效HarmonyOS NEXT编程:ArkTS数据结构优化与属性访问最佳实践
harmonyos·harmonyos next
盖世栗子17 小时前
鸿蒙OS(HarmonyOS),RelativeContainer的用法和特性
harmonyos
拔丝豌豆17 小时前
【HarmonyOS Next】跨模块交互的事件路由
harmonyos
MardaWang17 小时前
HarmonyOS 应用程序包结构 (编译态)
华为·harmonyos