HarmonyOS鸿蒙开发如何读取工程目录中的非图片资源文件(pdf,word,txt等等)的uri

尝试

context.filesDir; // 获取沙箱路径
context.cacheDir
context.tempDir
context.databaseDir
context.preferencesDir
context.bundleCodeDir
context.distributedFilesDir
context.resourceDir

这些里面是找不到项目目录中的资源文件的

只能以二进制获取

而且文件必须保存在特定目录下,以yyyy.pdf为例

/src/main/resources/rawfile/yyyy.pdf

然后通过资源管理方式读取

需要引入的头文件有

import { filePreview } from '@kit.PreviewKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { resourceManager } from '@kit.LocalizationKit';
import { fileIo as fs, fileUri } from '@kit.CoreFileKit';
import { promptAction } from '@kit.ArkUI';

然后 读取文件

    let uiContext = getContext(this);
      let name:string = "yyyy.pdf";
      let fileName: string = name;
      let ssd:resourceManager.RawFileDescriptor = uiContext.resourceManager.getRawFdSync(name);
      uiContext.resourceManager.getRawFileContent(name, (error: BusinessError, value: Uint8Array) => {
        if (error != null) {
          console.error("error is " + error);
        } else {

            //这里获取到文件二进制数据 然后进行下一步操作
        }
      });
    } catch (error) {

    }

将文件写入沙盒路径获取uri

        let context = getContext(this);
        let fileDir = context.filesDir; // 获取沙箱路径


        let filePath = fileDir + '/' +  fileName;
        let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // 创建文件
        let uri = fileUri.getUriFromPath(filePath); // 获取uri

        let writeLen = fs.writeSync(file.fd, value.buffer); // 写入文件
        console.info("write data to file succeed and size is:" + writeLen);
        fs.closeSync(file);

uri成功得到

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-02 06:00:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-02 06:00:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-02 06:00:01       82 阅读
  4. Python语言-面向对象

    2024-02-02 06:00:01       91 阅读

热门阅读

  1. Bi-Lstm+crf命名实体识别任务中crf的作用

    2024-02-02 06:00:01       47 阅读
  2. python魔法函数[全面]

    2024-02-02 06:00:01       63 阅读
  3. 网课:[CQOI2009]中位数图——牛客(疑问)

    2024-02-02 06:00:01       56 阅读
  4. redis百万级数据量预热方案

    2024-02-02 06:00:01       47 阅读
  5. LeetCode --- 2032. Two Out of Three 解题报告

    2024-02-02 06:00:01       46 阅读
  6. elementUI表单校验的几个方法区分

    2024-02-02 06:00:01       45 阅读
  7. Redis Cluster

    2024-02-02 06:00:01       53 阅读
  8. 15-RESTful风格-简化注解

    2024-02-02 06:00:01       51 阅读
  9. Python——turtle库笔记②

    2024-02-02 06:00:01       56 阅读
  10. Linux调优相关命令汇总

    2024-02-02 06:00:01       50 阅读