#鸿蒙学习大百科#如何读取文本文件中指定位置的内容?

如何读取文本文件中指定位置的内容?

HarmonyOS
2024-10-16 08:49:59
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
耗子煨汁r
import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { BusinessError } from '@kit.BasicServicesKit';
import { Options } from '@kit.CoreFileKit';
import { ReadTextOptions } from '@kit.CoreFileKit';

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;
  build() {
    Row() {
      Column() {
        Text("Hello")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let applicationContext = this.context.getApplicationContext();
            let cacheDir = applicationContext.cacheDir;
            let dirPath = cacheDir + "/aaa";
            let readTextOption: ReadTextOptions = {
              offset: 1,
              length: 2,
              encoding: 'utf-8'
            };
            fs.open(dirPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE).then((file: fs.File) => {
              fs.readText(file.path,readTextOption, (err: BusinessError , str: string) => {
                if (err) {
                  console.error("read failed with error message: " + err.message + ", error code: " + err.code);
                } else {
                  console.info("readText succeed:" + str);
                }
              })
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

文件中内容:Hello

打印结果:readText succeed:el

分享
微博
QQ
微信
回复
2024-10-16 15:18:05
相关问题
HarmonyOS 如何进行文本文件读取
200浏览 • 1回复 待解决
#鸿蒙学习大百科#什么是用户文件
222浏览 • 0回复 待解决