前言

在OpenHarmony应用开发中,编译构建任务流里读写文件是较为常见的功能。下文会以一个完整的示例为大家讲述如何实现此功能。

开发环境

DevEco Studio: DevEco Studio 6.0.0 Release(Build Version: 6.0.0.858)

开发流程

前置步骤

  1. 创建新工程。
  2. 预置文件pdftest.pdfsrc/main/resources/rawfile目录下。

新增hvigor任务

在根目录hvigorfile.ts里修改为以下代码

import { appTasks, OhosHapContext, OhosPluginId } from '@ohos/hvigor-ohos-plugin';
import { hvigor, FileUtil } from '@ohos/hvigor';
import path from "path";

hvigor.nodesEvaluated(() => {
  // 等待全部节点加载完成之后获取子节点信息
  hvigor.getRootNode().subNodes(subNode => {
    const hapContext = subNode.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext;
    const moduleName = hapContext?.getModuleName() ?? "";
    const moduleJsonOpt = hapContext?.getModuleJsonOpt() ?? "";
    console.debug(`moduleName: ${moduleName}`);
    if (moduleName === 'entry') {
      // 获取本地文件
      const filePath = path.resolve(hapContext.getModulePath(), 'src\\main\\resources\\rawfile\\pdftest.pdf');
      console.debug(`filePath: ${filePath}`);
      if (FileUtil.exist(filePath)) {
        console.log(`File exists: ${filePath}`);
      } else {
        console.log(`File doesn't exist: ${filePath}`);
      }
    }
  });
})

export default {
  system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: []       /* Custom plugin to extend the functionality of Hvigor. */
}

编译验证

  1. 编译工程,可以看到编译日志里打印了如下日志:
    moduleName: entry
    filePath: C:\Users\Winslei\DevEcoStudioProjects\MyApplication\entry\src\main\resources\rawfile\pdftest.pdf
    File exists: C:\Users\Winslei\DevEcoStudioProjects\MyApplication\entry\src\main\resources\rawfile\pdftest.pdf
    
Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐