写入文件,将缓冲区数据写入到指定的文件里

将缓冲区数据写入到指定的文件里

HarmonyOS
2024-05-20 21:57:16
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

核心代码解释

import fs from '@ohos.file.fs'; 
import common from '@ohos.app.ability.common'; 
@Entry 
@Component 
struct Index { 
  @State message: string = 'Hello World'; 
 
  createFile(filePath : string , buffer : ArrayBuffer | string){ 
    let cacheDir = getContext(this).cacheDir 
    // 新建并打开文件 
    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 
    // 写入一段内容至文件 
    let writeLen = fs.writeSync(file.fd, buffer); 
    console.info("The length of str is: " + writeLen); 
    // 从文件读取一段内容 
    let buf = new ArrayBuffer(1024); 
    let readLen = fs.readSync(file.fd, buf, { offset: 0 }); 
    // console.info("the content of file: " + String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); 
    // 关闭文件 
    fs.closeSync(file); 
  } 
 
  build() { 
    Row() { 
      Column() { 
        Text(this.message) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
        Button() 
          .onClick(()=>{ 
            //需要写入的文件(空文件) 
            let filePath1 = getContext(this).filesDir + "/test1.txt"; 
            let buf1 = new ArrayBuffer(4096); 
            this.createFile(filePath1,buf1) 
            let file1 = fs.openSync(filePath1, fs.OpenMode.READ_WRITE); 
 
            //创建文件 需要读取的文件 
            let filePath2 = getContext(this).filesDir + "/test2.txt"; 
            this.createFile(filePath2,"write in file") 
            //打开创建的文件读入 
            let file2 = fs.openSync(filePath2, fs.OpenMode.READ_WRITE); 
            let buf = new ArrayBuffer(4096); 
            //读入到缓冲区 
            fs.readSync(file2.fd, buf); 
            fs.closeSync(file2); 
            //将缓冲区内容写入到新文件内 
            fs.write(file1.fd,buf) 
            fs.closeSync(file1); 
          }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
分享
微博
QQ
微信
回复
2024-05-22 15:45:53
相关问题
自定义构建任务写入文件
330浏览 • 1回复 待解决
写入文件有大小限制吗?
364浏览 • 1回复 待解决
润和Neptune(W800)文件不能写入
6455浏览 • 3回复 已解决
innodb数据和binlog谁先写入
993浏览 • 1回复 待解决
如何docker容器中文件复制主机?
1125浏览 • 1回复 待解决
clog写入效率怎么监控?
2437浏览 • 1回复 待解决
PolarDB 行如何写入块?
1336浏览 • 1回复 待解决
求大佬告知bigint要怎么写入rdb
449浏览 • 1回复 待解决
如何打开指定文件夹,选择文件返回
7305浏览 • 1回复 待解决
如何easymock数据插入数据库?
917浏览 • 1回复 待解决
Native rdb写入是否有线程安全管理
680浏览 • 1回复 待解决