文件管理工具类(Harmony OS)

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

工具类源码,如下:

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、初始化,如下:

//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、在页面使用,如下:

//1、引入工具包
import FileManagerUtils from '../utils/FileManagerUtils'

@Entry
@Component
struct Index {
  aboutToAppear(){

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

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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值