元服务——6、json文件处理

2024-11-30 16:14:03
20次阅读
1个评论

一、创建微服务

选择atomic service

image.png

二、json权限获取

entry\src\main\resources\base\element\string.json 添加代码

{
  "name": "read_media_permission",
  "value": "申请读取媒体文件权限,便于应用访问您的照片、视频等媒体资料。"
}

image.png

entry\src\main\module.json5

"requestPermissions": [
  {
    "name": "ohos.permission.READ_MEDIA",
    "reason": "$string:read_media_permission",
    "usedScene": {
      "abilities": [
        "MainAbility"
      ],
      "when": "always"
    }
  }
],

image.png 改完后右上角同步一下

三、写入文件操作

导包,写在pages/index.etc最上面

import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer, List } from '@kit.ArkTS';

写入函数


@State fileName :string = '/test.txt' ;



createFile(){
  // 获取应用文件路径
  let context = getContext(this) as common.UIAbilityContext;
  let filesDir = context.filesDir;
  // 新建并打开文件
  let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE);
  // 将集合转换成json序列化对象存储到文件中
  let writeLen = fileIo.writeSync(file.fd, "写入的信息");
  console.info("字符串长度: " + writeLen);
  // 从文件读取一段内容
  console.info(filesDir)
  // 关闭文件
  fileIo.closeSync(file);
}

在d盘下出现text.txt文件,里面是写入的内容 如果只有c盘,需要以管理员身份运行DevEco Studio

四、读取文件操作

  readFile():string{
    let context = getContext(this) as common.UIAbilityContext;
    if (!context) {
      console.info("无法获取有效的上下文");
      return "";
    }
    let filesDir = context.filesDir;
    // 新建并打开文件
    let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.READ_ONLY|fileIo.OpenMode.CREATE);

    let bufferSize = 1024;
    let arrayBuffer = new ArrayBuffer(bufferSize);
    class Option {
      public offset: number = 0;
      public length: number = bufferSize;
    }
    let option = new Option();
    let content: string = "";
    let readLen: number=0;
    do {
      // 读取文件内容到数组缓冲区
      readLen = fileIo.readSync(file.fd, arrayBuffer, option);
      if (readLen > 0) {
        let buf = buffer.from(arrayBuffer, 0, readLen);
        content += buf.toString();
        // 更新下一次读取的偏移量,继续从文件后续位置读取
        option.offset += readLen;
        console.info(buf.toString())
      }
    } while (readLen === bufferSize); //判断+赋值
    console.info("内容是:"+content)
    // 关闭文件
    fileIo.closeSync(file);
    return content;
  }
  //将字符串反序列化 (解析)
  backModel(){
    this.info = JSON.parse(this.readFile());
  }

六、完整代码

import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer, List } from '@kit.ArkTS';
import { Orders } from '../model/Orders';
import { DocumentScanner } from '@hms.ai.DocumentScanner';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State fileName :string = '/test.txt' ;
  // @State info :Orders | null = null ;
  @State info :Array<Orders> | null = null ;

  aboutToAppear() :void{
    this.createFile();
    console.info("初始化完毕")
    this.backModel();
  }

  createFile(){
    // 获取应用文件路径
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir = context.filesDir;
    // 新建并打开文件
    let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE);
    //字符串序列化
    //单个
    // let o :Orders = new Orders();
    // o.no=1;
    // o.name="刘德华";
    // o.getTime="1998-10-10 06:06:06";
    // o.score = 98;
    //多个
    let arr :Array<Orders> = new Array<Orders>();
    for (let index = 0; index < 10; index++) {
      let o:Orders = new Orders();
      o.no = index+1;
      o.name =  "刘德华" + index;
      o.getTime = "1998-10-10 06:06:06"+index;
      o.score = 80+index;
      arr.push(o);
    }
    // 将集合转换成json序列化对象存储到文件中
    // 反序列化
    let writeLen = fileIo.writeSync(file.fd, JSON.stringify(arr));
    console.info("字符串长度: " + writeLen);
    // 从文件读取一段内容
    console.info(filesDir)
    // 关闭文件
    fileIo.closeSync(file);
  }

  readFile():string{
    let context = getContext(this) as common.UIAbilityContext;
    if (!context) {
      console.info("无法获取有效的上下文");
      return "";
    }
    let filesDir = context.filesDir;
    // 新建并打开文件
    let file = fileIo.openSync(filesDir + this.fileName, fileIo.OpenMode.READ_ONLY|fileIo.OpenMode.CREATE);

    let bufferSize = 1024;
    let arrayBuffer = new ArrayBuffer(bufferSize);
    class Option {
      public offset: number = 0;
      public length: number = bufferSize;
    }
    let option = new Option();
    let content: string = "";
    let readLen: number=0;
    do {
      // 读取文件内容到数组缓冲区
      readLen = fileIo.readSync(file.fd, arrayBuffer, option);
      if (readLen > 0) {
        let buf = buffer.from(arrayBuffer, 0, readLen);
        content += buf.toString();
        // 更新下一次读取的偏移量,继续从文件后续位置读取
        option.offset += readLen;
        console.info(buf.toString())
      }
    } while (readLen === bufferSize); //判断+赋值
    console.info("内容是:"+content)
    // 关闭文件
    fileIo.closeSync(file);
    return content;
  }
  //将字符串反序列化 (解析)
  backModel(){
    this.info = JSON.parse(this.readFile());
  }

  build() {
    Column() {
      // Text(){
      //   Span(this.info?.no.toString())
      //   Span(this.info?.name.toString())
      //   Span(this.info?.getTime.toString())
      //   Span(this.info?.score.toString())
      // }.fontSize(36)
      ForEach(this.info,(o:Orders,index)=>{
        Column(){
          Text(o.no.toString())
          Text(o.name.toString())
          Text(o.getTime.toString())
          Text(o.score.toString())
        }
      })
      Button(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        }).onClick(()=>{
        console.info(this.readFile())
      })
    }
    .height('100%')
    .width('100%')
  }

}

image.png

收藏01
    2024-11-30 20:08:28

    QwQ

登录 后评论。没有帐号? 注册 一个。