HarmonyOS fs.openSync\(filePath, fs.OpenMode.CREATE\) 报错 \{"code":13900002\}?

@kit.CoreFileKit 中 openSync,OpenMode.CREATE 模式,希望实现:不存在则创建文件,

但是实际上一直报错:{“code”:13900002 } ,查到意思是 13900002:没有这个文件或目录

不存在时不是应该实现创建功能吗,为什么会报错,应该使用什么方法代替?

代码如下:

import { fileIo as fs } from '@kit.CoreFileKit';
const files = {}
try {
  console.log('-------filePath-----', filePath) // 可以正常输出
  files[filePath] = fs.openSync(filePath, fs.OpenMode.CREATE)
  console.log('-------filePath-22222222----', filePath) // 没有执行到这里
} catch (err) {
  console.error('writeFileOffset Error:', JSON.stringify(err)) // 一直走这里,报错信息 :{"code":13900002}
  throw err
}
阅读 570
1 个回答

带了create mode时,如果报错{13900002},是由于某级父目录不存在,无法执行创建动作,需要排查下创建的路径是否缺失了父目录

推荐使用@ohos.file.fs (文件管理)的能力集:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-fs-V5\#fsmkdirsync11

示例代码如下:

import fs from '@ohos.file.fs';
import { promptAction } from '@kit.ArkUI';

@Entry
@Component
struct Index2 {
  @State message: string = 'Hello World';
  @State filesDir: string = ''

  get() {
    let context = getContext(this)
    this.filesDir = context.filesDir;
    // let filePath = this.filesDir + "/aaa/bbb/test1.txt";
    let filePath = this.filesDir + "/www/aaa";
    if (!fs.accessSync(filePath, 0)) {
      fs.mkdirSync(filePath, true)
    }
    console.info("filePath: " + filePath);
    try {
      let file = fs.openSync(filePath+'/test1.txt', fs.OpenMode.CREATE);
      console.info("file fd: " + file.fd);
      fs.closeSync(file);
    } catch (e) {
      console.error('writeFileOffset Error:', JSON.stringify(e))
    }
  }

  build() {
    Column() {
      Button('点击').onClick(() => {
        this.get()
        promptAction.showToast({ message: `方法已执行` })
      })
    }.width('100%').height('100%').justifyContent(FlexAlign.Center)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进