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

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

相关推荐
花椒技术7 小时前
复杂直播业务做 RN 跨端,我们最后保留了哪些 Native 边界
react native·react.js·harmonyos
不羁的木木9 小时前
《HarmonyOS技术精讲》四:驱动开发入门 ── 标准外设与非标USB串口
驱动开发·华为·harmonyos
不羁的木木10 小时前
《HarmonyOS底部页签-沉浸光感组件实战》高级定制:图标出血与分割线
华为·harmonyos
Goway_Hui11 小时前
【鸿蒙原生应用开发--ArkUI--015】File-manager 文件管理器应用开发教程
华为·harmonyos
不羁的木木14 小时前
《HarmonyOS底部页签-沉浸光感组件实战》基础入门:认识HdsTabs容器与核心配置
华为·harmonyos
不羁的木木14 小时前
《HarmonyOS技术精讲》三:记忆链接 ── 跨场景数据融合
pytorch·华为·harmonyos
2501_9197490314 小时前
鸿蒙 Flutter 实战:image_crop 0.4.1 适配 3.27-ohos 全流程
flutter·华为·harmonyos
祭曦念14 小时前
鸿蒙应用的生命周期与页面跳转:从入门到实战
华为·harmonyos
轻口味15 小时前
HarmonyOS 6.1.1 全栈实战录 - 88 实战 Ability Kit 启动生命周期预热与快照恢复机
华为·harmonyos·鸿蒙
Goway_Hui15 小时前
【鸿蒙原生应用开发--ArkUI--013】Exercise-tracker 运动记录应用开发教程
华为·harmonyos