#夏日挑战赛# OpenHarmony eTS 常用文件操作管理 原创 精华

Buty9147
发布于 2022-6-16 23:55
浏览
1收藏

OpenHarmony eTS 常用文件操作管理

本文正在参加星光计划3.0 – 夏日挑战赛

@toc

1.介绍

文件管理是经常使用的功能了,常用操作包含,
打开文件目录,创建目录,打开文件,复制文件,从文件读取数据,将数据写入文件,基于文件路径打开文件流等等 ,那么eTS版本是如何实现的呢,那么我们今天就一起来看一下,本文只列举部分,更多接口可以参考:
https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-fileio-0000001168366687

2.使用步骤(Index.ets)

导入模块

import fileIo from '@ohos.fileio'

说明:使用该功能模块对文件/目录进行操作前,需要先获取其绝对路径。
文件管理常用操作

2.1. 获取文件路径

getOrCreateLocalDir 是获取Ability或应用放置数据文件的绝对路径(本地根目录)==(/data/accounts/account_0/appdata/ohos.samples.etsfileio/ohos.samples.etsfileio/ohos.samples.etsfileio.MainAbility)==
使用该目录时,需要在下级新建一个目录,如样例中的/files,否则会报Permission denied。如果是第一次调用,则将创建目录。

2.2. 获取文件流

在读文件和写文件是需要文件流

private stream: fileIo.Stream

//open stream from fd
this.stream = fileIo.fdopenStreamSync(writeFd, "r+")

2.3. 创建文件

create_fileIo() {
    try {
      this.oriPath = path + '/xxx.txt'
      //number fd - file descriptor.
      //0o2:读写打开。0o100:若文件不存在,则创建文件。
      //0o666:所有者具有读、写权限,所有用户组具有读、写权限,其余用户具有读、写权限。
      this.fd = fileIo.openSync(this.oriPath, 0o2 | 0o100, 0o666)

      prompt.showToast({ message: 'create_file success =>' + this.oriPath, duration: 2000 })
      console.log('FileIo fd =' + this.fd)

      fileIo.close(this.fd)
    } catch (error) {
      console.error('FileIo error=' + error)
    }
 }

2.4. 修改文件名

  rename_fileIo() {

    this.newPath = path + '/FileIo.txt'
    //文件重命名,原,新
    fileIo.renameSync(this.oriPath, this.newPath)
    

    prompt.showToast({ message: 'rename_file success =>' + this.newPath, duration: 2000 })
  }

2.5. 写入文件

  write_fileIo() {

    //number fd - file descriptor.
    //0o2:读写打开。0o100:若文件不存在,则创建文件。
    //0o666:所有者具有读、写权限,所有用户组具有读、写权限,其余用户具有读、写权限。
    let writeFd = fileIo.openSync(this.newPath, 0o2 | 0o100, 0o666)

    //open stream from fd
    this.stream = fileIo.fdopenStreamSync(writeFd, "r+")

    //write content
    let writelength = this.stream.writeSync(writeContent, {
      offset: 0,
      length: writeContent.length,
      position: 0,
      encoding: 'utf-8'
    })


    prompt.showToast({ message: 'write_fileIo success =>' + 'hello, fileIo', duration: 2000 })
    console.log('FileIo WriteLength = ' + writelength)


    this.stream.close()
    fileIo.close(writeFd)


  }

2.6. 读取文件

  read_fileIo() {


    //number fd - file descriptor.
    let readFd = fileIo.openSync(this.newPath, 0o0)

    //open stream from fd
    this.stream = fileIo.fdopenStreamSync(readFd, "r")


    //buf
    let buf = new ArrayBuffer(4096)

    //string len
    let length = this.stream.readSync(buf, { offset: 0, length: writeContent.length, position: 0 })


    //char to string
    this.readText = String.fromCharCode.apply(null, new Uint8Array(buf))


    prompt.showToast({ message: 'read_fileIo success', duration: 2000 })
    console.log('FileIo buf = ' + this.readText)
    console.log('FileIo length = ' + length)


    //关闭
    this.stream.close()
    fileIo.close(readFd)


  }

2.7. 删除文件

  delete_fileIo() {

    //删除其实是取消链接的含义
    fileIo.unlinkSync(this.newPath)


    prompt.showToast({ message: 'delete_file success', duration: 2000 })
  }

2.8. 创建目录和文件(DistributeDemo.ets)

//获取Ability或应用的分布式文件路径
context.getOrCreateDistributedDir().then((data) => {
//获取应用在内部存储上的文件路径
//context.getFilesDir().then((data) => {
//应用在内部存储上的缓存目录
//context.getCacheDir().then((data) => {
  path = data + '/tmp'
  console.log('FileIo path =' + path)
})

创建创建目录及文件

  create_dir() {
    //创建目录
    fileIo.mkdir(path)
      .then(data => {
        console.log(`FileIo mkdir succ`)

        let dir = fileIo.opendirSync(path)
        console.log(`FileIo mkdir succ=${JSON.stringify(dir)}`)

        //创建文件
        this.create_fileIo()
      })
      .catch(err => {
        console.error(`FileIo mkdir err=${err}`)
      })
  }

3.总结思考

一些调试心得:

  1. 如果运行起来也看不到报错,就是没反应,可以通过try/catch进行错误定位。
  2. 如果在OpenHarmony这边调试过程中不确定是写的不对还是功能还不是很完善,可以对比HarmonyOS的调试结果进行分析。
  3. 除了getOrCreateLocalDir 还有几个类型的目录,如:
    getOrCreateDistributedDir 分布式文件路径 ==(/data/storage/el2/distributedfiles/entry==
    getFilesDir 获取应用在内部存储上的文件路径 == (/data/storage/el2/base/haps/entry/files)==
    getCacheDir 应用在内部存储上的缓存目录 ==(/data/storage/el2/base/haps/entry/cache)==,
    这几个目录,在使用时,则无需再下一级添加子目录,否则会报No such file or directory。
    如果想加一个子目录,那就需要先创建该目录,再创建文件。

4.完整代码

直接附件下载

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
FileIo.zip 519.8K 176次下载
已于2022-6-17 00:06:40修改
3
收藏 1
回复
举报
1条回复
按时间正序
/
按时间倒序
红叶亦知秋
红叶亦知秋

心得很有用,学习了

回复
2022-6-17 10:01:30
回复
    相关推荐