HarmonyOS 鸿蒙Next中如何获取手机里的txt和word文本

HarmonyOS 鸿蒙Next中如何获取手机里的txt和word文本 cke_389.png

cke_1086.png老是有报错搞了好久了没什么进展,有没有大神帮帮我


更多关于HarmonyOS 鸿蒙Next中如何获取手机里的txt和word文本的实战教程也可以访问 https://www.itying.com/category-93-b0.html

7 回复

背景知识:

楼主可以使用 picker.DocumentViewPicker 方法获取手机中的指定文件。然后将其文件 uri 传入FileUtils.readFileContent() 中读取出文件内容。

问题解决:

示例代码:

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

@Entry
@Component
struct ExcelPage {
    @State message: string = 'Excel';
    context = this.getUIContext().getHostContext() as common.Context

    build() {
        Column() {
            Button(this.message)
                .fontSize(20)
                .fontColor(Color.White)
                .fontWeight(FontWeight.Bold)
                .onClick(()=>{
                    try {
                        let documentSelectOptions = new picker.DocumentSelectOptions();
                        let documentPicker = new picker.DocumentViewPicker(this.context);
                        documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) =>  {
                            console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' + JSON.stringify(documentSelectResult));
                            //读取文件
                            FileUtils.readFileContent(documentSelectResult[0])
                        }).catch((err: BusinessError) => {
                            console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
                        });
                    } catch (error) {
                        let err: BusinessError = error as BusinessError;
                        console.error(`DocumentViewPicker failed with err, code is: ${err.code}, message is: ${err.message}`);
                    }
                })
        }
        .height('100%')
        .width('100%')
    }
}


//读取内容工具类
import fs from '@ohos.file.fs';
import { util, buffer } from '@kit.ArkTS';

export class FileUtils {

    static readFileContent(uri: string) {
        let file: fs.File | undefined;
        try {
            file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
            const stat = fs.statSync(file.fd);
            const buffer = new ArrayBuffer(stat.size);
            fs.readSync(file.fd, buffer); // 同步读取到缓冲区
            const content: string =
                new util.TextDecoder().decodeToString(new Uint8Array(buffer)) // 转为字符串
            console.info('文件内容:', content);
        } catch (error) {
            console.error('读取失败:', error);
        } finally {
            if (file) {
                fs.closeSync(file);
            } // 必须关闭文件句柄
        }
    }
}

更多关于HarmonyOS 鸿蒙Next中如何获取手机里的txt和word文本的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


获取用户设备内的txt和word文件,可通过**系统文件选择器(FilePicker)**实现。用DocumentViewPicker选择文件:

import { document } from '@kit.CoreFileKit';

import { BusinessError } from '@kit.BasicServicesKit';

// 创建文档选择器实例

let documentPicker = new document.DocumentViewPicker();

// 设置文件类型过滤(示例中过滤txt和doc/docx)

let options: document.DocumentSelectOptions = {

  fileTypes: ['txt', 'doc', 'docx']

};

// 调用选择器并获取文件URI

documentPicker.select(options).then((uris) => {

  console.info('选择的文件URI:', uris);

  // 此处需将URI转换为实际文件路径并读取内容

}).catch((err: BusinessError) => {

  console.error('文件选择失败:', err.code, err.message);

});

通过@kit.FileManagementKit的documentViewPicker接口选择文件,示例代码如下

import { documentViewPicker } from '[@kit](/user/kit).FileManagementKit';

async function selectFile() {
  let picker = new documentViewPicker.DocumentViewPicker();
  let options = {
    types: ['text/plain', 'application/msword'], // 指定需要选择的文件类型
  };
  try {
    let fileList = await picker.select(options);
    if (fileList.length > 0) {
      return fileList.uri; // 获取选中文件的URI
    }
  } catch (error) {
    console.error('选择文件失败:', error);
  }
}

【背景知识】

[@ohos.file.picker (选择器)](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-picker):选择器(Picker)是一个封装DocumentViewPicker、AudioViewPicker、PhotoViewPicker的API模块,具有选择与保存的能力。应用可以选择使用以下API来实现文件的选择和保存的功能。该类接口,需要应用在界面UIAbility中调用,否则无法拉起FilePicker应用、AudioPicker应用或PhotoPicker应用。

[@ohos.file.fs (文件管理)](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-fs):该模块为基础文件操作API,提供基础文件操作能力,包括文件基本管理、文件目录管理、文件信息统计、文件流式读写等常用功能。

【参考方案】

可参考实现选择和查看文件功能示例,通过@ohos.file.picker、@ohos.file.fs等接口,实现了拉起文档编辑保存的效果。

  • 拉起picker选择文件、拉起picker保存文件的功能封装在Index.ets,源码参考:Index.ets
    • 使用new picker.DocumentViewPicker来创建文件picker实例,使用documentPicker.select来拉起picker选择文件,使用documentPicker.save来拉起picker保存文件,接口参考:@ohos.file.picker
  • 编辑文件并保存的功能封装在EditFile.ets,源码参考:EditFile.ets
    • 使用fs.openSync、fs.writeSync、fs.readSync、fs.closeSync分别用来打开文件、写文件、读文件、关闭文件,接口参考:@ohos.file.fs

可以参考这个

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

@Entry
@Component
struct PagePickerDocument {
  @State message: string = 'Hello World';

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('PagePickerDocumentHelloWorld')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(async () => {
          this.message = 'Welcome';
          let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // 请确保this.getUIContext().getHostContext()返回结果为UIAbilityContext
          let documentPicker = new picker.DocumentViewPicker(context);
          let documentSelectOptions = new picker.DocumentSelectOptions();
          documentSelectOptions.fileSuffixFilters = ['txt']
          documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
            console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' + JSON.stringify(documentSelectResult));
            let uri: string = documentSelectResult[0];
            // 这里需要注意接口权限参数是fs.OpenMode.READ_ONLY。
            try {
              let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
              let arrayBuffer = new ArrayBuffer(1024);
              let content = '';
              let readLen = 0;
              do {
                readLen = fs.readSync(file.fd, arrayBuffer);
                content += buffer.from(arrayBuffer, 0, readLen).toString();
              } while (readLen > 0);
              fs.closeSync(file)
              console.info(content)
            } catch (error) {
              // TODO: Implement error handling.
            }
          }).catch((err: BusinessError) => {
            console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
          });
        })
    }
    .height('100%')
    .width('100%')
  }
}

在HarmonyOS Next中,使用@ohos.file.fs@ohos.file.picker模块访问文档。通过documentPicker选择文件,调用fs.readText读取txt内容。对于Word文档(.doc/.docx),需使用@ohos.file.convert进行解析提取文本。注意申请ohos.permission.READ_MEDIA权限。具体接口可查阅ArkTS API文档中FileIO相关部分。

在HarmonyOS Next中,获取手机里的txt和word文本需要使用文件管理API,并通过权限申请确保用户授权。以下是关键步骤:

  1. 申请存储权限:在module.json5中声明ohos.permission.READ_MEDIA权限,并在运行时通过requestPermissionsFromUser动态请求用户授权。

  2. 使用文件选择器:通过PhotoViewPickerDocumentViewPicker(具体根据文件类型选择)调用系统文件选择界面,让用户主动选择txt或docx文件。示例代码:

    import picker from '[@ohos](/user/ohos).file.picker';
    
    let documentPicker = new picker.DocumentViewPicker();
    documentPicker.select().then((uriList) => {
      // 处理返回的URI列表
    }).catch((err) => {
      console.error('文件选择失败', err);
    });
    
  3. 通过URI读取文件内容:使用[@ohos](/user/ohos).file.fs模块的API,根据返回的URI读取文件数据。例如:

    import fs from '[@ohos](/user/ohos).file.fs';
    
    let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
    let content = fs.readSync(file.fd);
    fs.closeSync(file);
    
  4. 错误处理:常见错误包括权限未授权、URI无效或文件格式不支持。确保权限已获取,并验证文件类型。

如果持续报错,请检查权限声明和动态申请逻辑,确认URI获取及文件操作步骤正确。可参考官方文档中的文件管理示例代码进行调试。

回到顶部