HarmonyOS 鸿蒙Next文件存储读取

HarmonyOS 鸿蒙Next文件存储读取 手机设备,可以读取到外部存储目录吗?我想创建日志文件到外部存储目录,方便用户可以打开,发送该文件给研发查问题

2 回复

系统应用在读取和操作系统文件时,可以申请ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORYohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY这两个受限权限来实现系统文件的访问。

三方应用在操作系统文件时,由于系统权限的管控,只能通过ohos.file.picker (选择器)来实现系统文件的访问。

外置存储设备(例如U盘)上的文件,全部以普通文件的形式呈现,和内置存储设备上的文档类文件一样,采用目录树的形式对外展示。需要使用DocumentViewPicker来实现系统文件的访问。

外置存储系统文件的访问,先用文件选择器把系统文件夹里的文件拷贝到沙箱,再对沙箱里的文件进行各种操作。具体方法是:调用DocumentViewPicker可以实现预览系统文件,再把选中的文件写入到对应的沙箱中。示例代码如下:

import { common } from '@kit.AbilityKit';
import { picker } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';

@Entry
@Component
struct Index {

  build() {
    Row() {
      Column() {
        Button('查看U盘文件并导入到沙箱')
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let context = getContext(this) as common.Context; // 请确保getContext(this)返回结果为UIAbilityContext
            let documentPicker = new picker.DocumentViewPicker(context);
            let documentSelectOptions = new picker.DocumentSelectOptions();
            // filePathList:选中的文件集合
            documentPicker.select(documentSelectOptions).then((filePathList: Array<string>) => {
              for (let i = 0; i < filePathList.length; i++) {
                let filePath = filePathList[i];
                let toPath = getContext().filesDir;
                let newFrom = filePath.substring(filePath.lastIndexOf("/"));
                toPath = toPath + newFrom
                let fromFile = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
                let toFile = fs.openSync(toPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
                fs.copyFileSync(fromFile.fd, toFile.fd, 0)
                console.info("成功将[" + filePath + "]文件拷贝到了沙箱")
              }
            }).catch((err: BusinessError) => {
              console.error('DocumentViewPicker.select failed with err: ' + err);
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
  1. 点击查看U盘文件并导入到沙箱按钮后,拉起了DocumentViewPicker。
  2. 点击MyUSB后可以浏览我的U盘。选中要拷贝的文件。
  3. 点击完成后,将U盘中的文件拷贝到沙箱中。

更多关于HarmonyOS 鸿蒙Next文件存储读取的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙Next)中,文件存储和读取主要通过FileFileReader等API实现。开发者可以使用File类创建、删除、重命名文件,以及获取文件信息。FileReader类则用于读取文件内容,支持同步和异步读取。此外,HarmonyOS提供了Storage模块,用于管理应用的文件存储路径,如内部存储和外部存储。开发者应遵循权限管理,确保应用在访问文件时获得必要的权限。

回到顶部