HarmonyOS 沙箱路径filesDir下无法使用open创建新文件

HarmonyOS
2024-12-25 15:24:58
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Excelsior_abit

请参考示例如下:

// 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%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
分享
微博
QQ
微信
回复
2024-12-25 18:41:38
相关问题
HarmonyOS 预览沙箱路径文件失败
701浏览 • 1回复 待解决
修改沙箱路径json文件的指定内容
3011浏览 • 1回复 待解决
ETs,对沙箱路径的json文件内容遍历
3890浏览 • 1回复 待解决
沙箱路径文件怎么拿取?
2581浏览 • 1回复 待解决
无法查看应用沙箱文件
1466浏览 • 1回复 待解决
fileio.open文件路径错误怎么回事啊?
3972浏览 • 1回复 待解决
在native侧创建file并保存进沙箱路径
1804浏览 • 1回复 待解决