如何对一个文件进行读写操作

如何对一个文件进行读写操作

HarmonyOS
2024-08-01 09:44:35
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
dickhome

需要使用基础文件操作接口:ohos.file.fs,开始访问之前需要获取文件的路径,以下为示例。

// 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);
}
分享
微博
QQ
微信
回复
2024-08-01 18:28:20
相关问题
基于PhotoViewPicker图片进行操作
410浏览 • 1回复 待解决
基于CameraKit相机进行操作
381浏览 • 1回复 待解决
一个更新操作有必要用到事务吗?
1929浏览 • 1回复 待解决
如何创建一个window?
99浏览 • 1回复 待解决
实现一个模拟文件下载的过程
105浏览 • 1回复 待解决