HarmonyOS 鸿蒙Next中如何获取手机里的txt和word文本
HarmonyOS 鸿蒙Next中如何获取手机里的txt和word文本
老是有报错搞了好久了没什么进展,有没有大神帮帮我
更多关于HarmonyOS 鸿蒙Next中如何获取手机里的txt和word文本的实战教程也可以访问 https://www.itying.com/category-93-b0.html
背景知识:
楼主可以使用 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);
}
}
可以参考这个
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,并通过权限申请确保用户授权。以下是关键步骤:
-
申请存储权限:在
module.json5
中声明ohos.permission.READ_MEDIA
权限,并在运行时通过requestPermissionsFromUser
动态请求用户授权。 -
使用文件选择器:通过
PhotoViewPicker
或DocumentViewPicker
(具体根据文件类型选择)调用系统文件选择界面,让用户主动选择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); });
-
通过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);
-
错误处理:常见错误包括权限未授权、URI无效或文件格式不支持。确保权限已获取,并验证文件类型。
如果持续报错,请检查权限声明和动态申请逻辑,确认URI获取及文件操作步骤正确。可参考官方文档中的文件管理示例代码进行调试。