HarmonyOS鸿蒙Next中如何使用fileIo进行文件读写操作?

HarmonyOS鸿蒙Next中如何使用fileIo进行文件读写操作? 我需要在应用沙箱中读写文件,fileIo 如何使用?如何读写文本文件和 JSON 文件?

3 回复

实现思路:

  1. 获取应用沙箱路径并拼接文件路径:
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';

const context = getContext(this) as common.UIAbilityContext;
const filePath = `${context.filesDir}/data.txt`;
  1. 使用 fileIo.open 和 fileIo.write 写入文件:
const file = fileIo.openSync(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
fileIo.writeSync(file.fd, 'Hello World');
fileIo.closeSync(file.fd);
  1. 使用 fileIo.read 读取文件内容:
const file = fileIo.openSync(filePath, fileIo.OpenMode.READ_ONLY);
const buffer = new ArrayBuffer(4096);
const readLen = fileIo.readSync(file.fd, buffer);
const content = String.fromCharCode(...new Uint8Array(buffer.slice(0, readLen)));
fileIo.closeSync(file.fd);
  1. 完整示例代码:
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { util } from '@kit.ArkTS';

class FileUtil {
  private context: common.UIAbilityContext;

  constructor(context: common.UIAbilityContext) {
    this.context = context;
  }

  getFilePath(fileName: string): string {
    return `${this.context.filesDir}/${fileName}`;
  }

  writeText(fileName: string, content: string): boolean {
    try {
      const filePath = this.getFilePath(fileName);
      const file = fileIo.openSync(filePath, 
        fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.TRUNC);
      const encoder = new util.TextEncoder();
      const buffer = encoder.encodeInto(content);
      fileIo.writeSync(file.fd, buffer.buffer);
      fileIo.closeSync(file.fd);
      return true;
    } catch (err) {
      console.error(`Write file failed: ${JSON.stringify(err)}`);
      return false;
    }
  }

  readText(fileName: string): string {
    try {
      const filePath = this.getFilePath(fileName);
      if (!fileIo.accessSync(filePath)) {
        return '';
      }
      const file = fileIo.openSync(filePath, fileIo.OpenMode.READ_ONLY);
      const stat = fileIo.statSync(file.fd);
      const buffer = new ArrayBuffer(stat.size);
      fileIo.readSync(file.fd, buffer);
      fileIo.closeSync(file.fd);
      const decoder = new util.TextDecoder();
      return decoder.decodeToString(new Uint8Array(buffer));
    } catch (err) {
      console.error(`Read file failed: ${JSON.stringify(err)}`);
      return '';
    }
  }

  writeJson<T>(fileName: string, data: T): boolean {
    return this.writeText(fileName, JSON.stringify(data));
  }

  readJson<T>(fileName: string, defaultValue: T): T {
    const content = this.readText(fileName);
    if (content) {
      try {
        return JSON.parse(content) as T;
      } catch {
        return defaultValue;
      }
    }
    return defaultValue;
  }

  deleteFile(fileName: string): boolean {
    try {
      const filePath = this.getFilePath(fileName);
      if (fileIo.accessSync(filePath)) {
        fileIo.unlinkSync(filePath);
      }
      return true;
    } catch (err) {
      console.error(`Delete file failed: ${JSON.stringify(err)}`);
      return false;
    }
  }

  fileExists(fileName: string): boolean {
    try {
      return fileIo.accessSync(this.getFilePath(fileName));
    } catch {
      return false;
    }
  }
}

// 使用示例
@Entry
@Component
struct FileOperationPage {
  private fileUtil: FileUtil = new FileUtil(getContext(this) as common.UIAbilityContext);
  @State content: string = '';
  @State savedContent: string = '';

  build() {
    Column({ space: 16 }) {
      Text('文件操作').fontSize(20).fontWeight(FontWeight.Bold)

      TextArea({ placeholder: '输入内容', text: this.content })
        .height(150)
        .onChange((value: string) => {
          this.content = value;
        })

      Row({ space: 12 }) {
        Button('保存').onClick(() => {
          if (this.fileUtil.writeText('note.txt', this.content)) {
            console.info('保存成功');
          }
        })

        Button('读取').onClick(() => {
          this.savedContent = this.fileUtil.readText('note.txt');
        })

        Button('删除').onClick(() => {
          this.fileUtil.deleteFile('note.txt');
          this.savedContent = '';
        })
      }

      if (this.savedContent) {
        Text('已保存内容:').fontSize(14).fontColor('#666')
        Text(this.savedContent)
          .fontSize(14)
          .padding(12)
          .backgroundColor('#F5F5F5')
          .borderRadius(8)
          .width('100%')
      }
    }
    .width('100%')
    .padding(16)
  }
}

更多关于HarmonyOS鸿蒙Next中如何使用fileIo进行文件读写操作?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,使用fileIo进行文件读写操作,需导入@ohos.file.fs模块。通过fs.openSync打开文件获取fd,fs.writeSync写入数据,fs.readSync读取数据,最后用fs.closeSync关闭fd。注意操作前需申请相应文件权限。

在HarmonyOS Next中,使用fileIo进行文件读写操作的核心是调用@ohos.file.fs文件管理模块的API。所有操作都应在应用沙箱目录(如context.filesDir)内进行。

以下是关键步骤和代码示例:

1. 导入模块

import fs from '@ohos.file.fs';

2. 获取沙箱文件路径并创建文件对象 通常使用应用上下文提供的目录来构建完整路径:

// 在UIAbility或AbilityStage中获取上下文
let context = ...; // 例如 this.context

// 构建沙箱内文件路径
let filePath = context.filesDir + '/test.txt'; // 文本文件
let jsonFilePath = context.filesDir + '/data.json'; // JSON文件

3. 写入文本文件

// 准备要写入的字符串
let textContent: string = 'Hello, HarmonyOS Next!';

// 写入文件
try {
  fs.writeTextSync(filePath, textContent);
  console.log('文本写入成功');
} catch (err) {
  console.error(`写入失败: ${err.code}, ${err.message}`);
}

4. 读取文本文件

try {
  let content: string = fs.readTextSync(filePath);
  console.log(`读取内容: ${content}`);
} catch (err) {
  console.error(`读取失败: ${err.code}, ${err.message}`);
}

5. 写入JSON文件

let jsonData = {
  name: 'HarmonyOS',
  version: 'Next'
};

try {
  // 将对象转换为JSON字符串后写入
  fs.writeTextSync(jsonFilePath, JSON.stringify(jsonData, null, 2));
  console.log('JSON写入成功');
} catch (err) {
  console.error(`JSON写入失败: ${err.code}, ${err.message}`);
}

6. 读取并解析JSON文件

try {
  let jsonString: string = fs.readTextSync(jsonFilePath);
  let parsedData = JSON.parse(jsonString);
  console.log(`解析后的数据: ${JSON.stringify(parsedData)}`);
} catch (err) {
  console.error(`JSON读取或解析失败: ${err.code}, ${err.message}`);
}

关键点说明:

  • writeTextSyncreadTextSync是同步方法。对于大文件或避免阻塞UI,请考虑使用异步版本writeTextreadText
  • 首次写入时,如果文件不存在,系统会自动创建。
  • 确保在module.json5中申请必要的文件访问权限(对于沙箱内操作,通常不需要额外权限)。
  • 操作路径必须限制在应用沙箱内,访问外部路径需要用户授权并使用不同的API。

这种模式确保了应用数据的私有性和安全性,符合HarmonyOS Next的应用沙箱规范。

回到顶部