HarmonyOS 鸿蒙Next 沙箱路径filesDir下无法使用open创建新文件
HarmonyOS 鸿蒙Next 沙箱路径filesDir下无法使用open创建新文件
根据文档 https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/app-file-access-V5 中介绍,准备操作context.filesDir下的文件。当目录下文件不存在的时候,按照文档的介绍使用
let file = fs.openSync(filesDir + ‘/test.txt’, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);进行操作,直接触发异常了。
换成let fileStream = fileIo.createStreamSync(rawfilenamemp3, “w+”);是可以正常创建文件并进行后续写入等操作。请问这是什么原因呢? 感觉opensync接口无法创建不存在的文件?
let file = fs.openSync(filesDir + ‘/test.txt’, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);进行操作,直接触发异常了。
换成let fileStream = fileIo.createStreamSync(rawfilenamemp3, “w+”);是可以正常创建文件并进行后续写入等操作。请问这是什么原因呢? 感觉opensync接口无法创建不存在的文件?
更多关于HarmonyOS 鸿蒙Next 沙箱路径filesDir下无法使用open创建新文件的实战教程也可以访问 https://www.itying.com/category-93-b0.html
        
          2 回复
        
      
      
        试下下面的代码呢
// pages/xxx.ets
import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer } from '@kit.ArkTS';
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
function createFile(): void {
  // 新建并打开文件
  let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  // 写入一段内容至文件
  let writeLen = fs.writeSync(file.fd, "Try to write str.");
  console.info("The length of str is: " + writeLen);
  // 从文件读取一段内容
  let arrayBuffer = new ArrayBuffer(1024);
  let readOptions: ReadOptions = {
    offset: 0,
    length: arrayBuffer.byteLength
  };
  let readLen = fs.readSync(file.fd, arrayBuffer, readOptions);
  let buf = buffer.from(arrayBuffer, 0, readLen);
  console.info("the content of file: " + buf.toString());
  // 关闭文件
  fs.closeSync(file);
}
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  build() {
    Column() {
      Text(this.message)
        .onClick(()=>{
          createFile();
        })
    }
    .height('100%')
    .width('100%')
  }
}
更多关于HarmonyOS 鸿蒙Next 沙箱路径filesDir下无法使用open创建新文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
        
      
                  
                  
                  

