HarmonyOS 鸿蒙Next中外置存储文件的读写

HarmonyOS 鸿蒙Next中外置存储文件的读写 手机APP与外置OTG存储设备的通信,如何操作外置存储器中的sqlite数据库文件或进行文件的读写。

3 回复

【背景知识】

  • 三方应用在操作手机文件时,可以通过ohos.file.picker来实现文件的访问。
  • 外置存储设备(例如U盘)上的文件,全部以普通文件的形式呈现,和内置存储设备上的文档类文件一样,采用目录树的形式对外展示。需要使用DocumentViewPicker来实现系统文件的访问。

【解决方案】

通过picker来访问用户相关文件,拉起对应的应用,引导用户完成界面操作,接口本身无需申请权限。 外置存储系统文件的访问,先用文件选择器把系统文件夹里的文件拷贝到沙箱,再对沙箱里的文件进行各种操作。 具体方法是:调用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 = this.getUIContext().getHostContext() as common.Context
            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%')
  }
}
  • 点击查看U盘文件并导入到沙箱按钮后,拉起了DocumentViewPicker。
  • 点击MyUSB后可以浏览我的U盘。选中要拷贝的文件。
  • 点击完成后,成功将U盘中的两个文件拷贝到了沙箱。

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


在HarmonyOS Next中,外置存储文件读写通过@ohos.file.fs模块实现。使用fs.access检查存储权限,fs.open打开文件,fs.readfs.write进行读写操作。需在module.json5中声明ohos.permission.READ_MEDIAohos.permission.WRITE_MEDIA权限。外置存储路径通过@ohos.file.environmentgetExternalStorageDir获取。注意使用fs.sync确保数据同步。

在HarmonyOS Next中,通过OTG连接外置存储设备后,可以使用@ohos.fileio@ohos.data.relationalStore模块进行文件与数据库操作。首先通过USBManager获取外设访问权限,确认挂载路径后,使用fileio接口读写文件(如复制、修改)。若需操作SQLite数据库,可通过relationalStore.getRdbStore以指定路径打开外置数据库文件,并执行SQL查询或事务。注意权限声明需在config.json中配置USB设备访问和存储读写权限。

回到顶部