首先从HarmonyOS官网UTD配置列表当中确认当前格式文件是否为HarmonyOS默认支持的文件类型,如果不是,则参看以下步骤自定义文件类型。实现方案如下:
{
"UniformDataTypeDeclarations": [
{
"TypeId": "com.example.myapplication.suffix1",
"BelongingToTypes": ["general.file"],
"FilenameExtensions": [".suffix1"],
"MIMETypes": ["application/suffix1"],
"Description": "自定义类型文件suffix1",
"ReferenceURL": ""
},
{
"TypeId": "com.example.myapplication.suffix2",
"BelongingToTypes": ["general.file"],
"FilenameExtensions": [".suffix2"],
"MIMETypes": ["application/suffix2"],
"Description": "自定义类型文件suffix2",
"ReferenceURL": ""
}
]
} {
"module": {
// ...
"abilities": [
{
// ...
"skills": [
// ...
{
"actions": [
"ohos.want.action.viewData"
],
"uris": [
{
"scheme": "file",
"type": "com.example.myapplication.suffix1",
"linkFeature": "FileOpen"
},
{
"scheme": "file",
"type": "com.example.myapplication.suffix2",
"linkFeature": "FileOpen"
}
]
}
]
}
],
// ...
}
} import { UIAbility, Want } from '@kit.AbilityKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';
export default class EntryAbility extends UIAbility {
// ...
onNewWant(want: Want): void {
let uri = want.uri;
if (!uri) {
return;
}
try {
// 根据待打开文件的URI进行相应操作。例如同步读写的方式打开URI获取file对象
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
console.info(`Succeed to open file.${file.fd}`);
let buf = new ArrayBuffer(4096);
fs.readSync(file.fd, buf);
// 案例以文本文件为例
console.info(`文件内容:${buffer.from(buf)}`);
} catch (err) {
let error: BusinessError = err as BusinessError;
console.error(`Failed to open file openSync, code: ${error.code}, message: ${error.message}`);
}
}
}