HarmonyOS鸿蒙Next中怎么获取文件的扩展名
HarmonyOS鸿蒙Next中怎么获取文件的扩展名 我想在沙箱里选择文件的时候,获取文件的扩展名,应该怎么实现?
解析文件扩展名
获取到文件名(或整个URI字符串)后,使用字符串方法截取扩展名。常用两种方式:
-
使用
split()与pop():将字符串按点号分割,取最后一段。const fileType = fileName.split('.').pop(); // 得到扩展名,如 "jpg" -
使用
lastIndexOf()与substring():定位最后一个点号位置,截取其后的部分。const dotIndex = fileName.lastIndexOf('.'); const fileType = fileName.substring(dotIndex + 1);
上面两种方式得到的 fileType 是不带点的,需要的话加上去即可。
更多关于HarmonyOS鸿蒙Next中怎么获取文件的扩展名的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
学习了
可以,能拿到。别直接对整段 URI 做 split(’.’),更稳的是先用官方 fileUri.FileUri 取文件名,再截最后一个点;如果还要按类型分流,再配合 UTD。依据是 fileUri.FileUri.name 能直接返回文件名,uniformTypeDescriptor.getUniformDataTypesByFilenameExtension() 可按后缀查标准化类型。
const name = new fileUri.FileUri(uri).name
const pos = name.lastIndexOf(’.’)
const ext = pos >= 0 ? name.substring(pos) : ‘’
需要类型分流时再查 const utds = ext ? uniformTypeDescriptor.getUniformDataTypesByFilenameExtension(ext) : []。如果工程 API < 13,就先只取 ext。可查华为官方《fileUri(文件URI)》和《UTD预置列表》。
期待解决,
解析文件扩展名
在HarmonyOS Next中,可使用ArkTS字符串方法:const ext = fileName.substring(fileName.lastIndexOf('.')); 获取扩展名。或通过@ohos.file.fs的extname接口。


