鸿蒙开发之简易操作沙箱文件(API12)

561 阅读2分钟

1. 本文达到的目的

  • 简易实现创建文件,存入沙箱
  • 读取文件里的内容
  • 删除文件

2. 创建文件

  • 先创建一个文件管理类 FileManger
  • 导入fileIo
import { fileIo } from '@kit.CoreFileKit'
  • 通过上下文去获取沙箱路径
// getContext().filesDir  files文件沙箱路径
// 创建文件路径
let filePath = getContext().filesDir + '/' + fileName + '.txt'
  • 获取要创建的文件路径之后,使用openSync函数去创建文件,同时第二个参数设置为 fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE
  • 然后再使用 writeSync 去写入文件信息,写入完毕调用 closeSync 关闭文件
// fs和fileIo功能基本一致
import { fileIo } from '@kit.CoreFileKit'

export class FileManger {
  // 1.创建文件
  static createFile(fileName: string, fileContent: string) {
    // 1.1准备文件的路径()
    let filePath = getContext().filesDir + '/' + fileName + '.txt'
    // 1.2打开文件(如果没有这个文件,就会创建,就是file)
    const file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
    // 读取的话....文件的操作
    fileIo.writeSync(file.fd, fileContent)
    // 1.3关闭文件
    fileIo.closeSync(file)
    // 返回文件的路径
    return filePath
  }
}

3. 读取文件内容

  • 调用创建文件方法
const filePath = FileManger.createFile('test', '写入文本内容')
console.log('filePath:' + filePath)
// /data/storage/el2/base/haps/entry/files/test.txt
  • 此时文件内容已经创建 ,文件的路径为/data/storage/el2/base/haps/entry/files/test.txt
  • 我们可以通过编辑器的文件管理器查看, 已经创建成功

4. 删除文件

  • 使用unlinkSync api 删除文件
// fs和fileIo功能基本一致
import { fileIo } from '@kit.CoreFileKit'

export class FileManger {
  // 1.创建文件
  static createFile(fileName: string, fileContent: string) {
   ....
  }
  //  2.删除文件
  static delFilePath(filePath: string) {
    if (filePath) {
      // 以同步的方式删除一个文件
      fileIo.unlinkSync(filePath)
    }
  }
}
  • 调用
FileManger.delFilePath(filePath)

5. 完整代码

import { fileIo } from '@kit.CoreFileKit'

export class FileManger {
  // 1.创建文件
  static createFile(fileName: string, fileContent: string) {
    // 1.1准备文件的路径()
    let filePath = getContext().filesDir + '/' + fileName + '.txt'
    // 1.2打开文件(如果没有这个文件,就会创建,就是file)
    const file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
    // 读取的话....文件的操作
    fileIo.writeSync(file.fd, fileContent)
    // 1.3关闭文件
    fileIo.closeSync(file)
    // 返回文件的路径
    return filePath
  }

  //  2.删除文件
  static delFilePath(filePath: string) {
    if (filePath) {
      // 以同步的方式删除一个文件
      fileIo.unlinkSync(filePath)
    }
  }
}
  const filePath = FileManger.createFile('test', '文本内容')
  console.log('filePath:' + filePath)
  // FileManger.delFilePath(filePath)