OpenHarmony—文件管理系列之二
source link: https://os.51cto.com/article/703206.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
本系列记录团队openHarmony 的学习和实践中,所踩过的坑以及填坑的记录,可能社区已有分享相关的文档,但也不妨大家一起探讨。
一、获取指定路径下的文件列表
若需获取指定路径下的文件列表,可以通过直接调用 file.list 来获取,也可以通过先调用 context.getFilesDir 来获取到应用在内部存储上的文件路径,得到路径后通过调用 fileio.opendir 可以获取到存储路径下的文件。
**需注意:**file模块从 API Version 6开始不再维护,官方建议使用fileio模块。
1、file模块调用
getlist() {
file.list({
uri: 'internal://app/',
success: function(data) {
if(data.fileList.length) {
data.fileList.forEach(item=>{
console.log(JSON.stringify(item))
})
}
},
fail: function (data, code) {
console.error('call fail callback fail, code: ' + code + ', data: ' + data);
},
complete: function (data, code) {
console.info('call complete callback complete, code: ' + code + ', data: ' + data);
},
});
},
2、fileio模块调用
getFilesDirUri() {
context.getFilesDir()
.then((data) => {
console.info('getFilesDir res' + data); // data 内部存储目录
this.opendir(data)
}).catch((error) => {
console.error('getFilesDir err' + error.message);
})
},
async opendir(path) {
let dir = await fileio.opendir(path); // dir 管理目录
this.inquireFiles(dir);
},
async inquireFiles(dir) {
let dirent = await dir.read(); // 读取下一个目录项
if(dirent) {
console.log(dirent.name)
this.inquireFiles(dir); // 循环获取下一个目录下
}else {
dir.closeSync(); // 关闭目录,释放dir中的文件描述
}
},
二、文件管理api调用时发现的问题
1、注意设备的基线版本
远程模拟器的底层内核是基于 HarmonyOS实现的,因此在远程模拟器上可以调用实现的文件管理异步api。而底层内核基于OpenHarmony实现的设备,若无法成功调用文件管理异步api,那么就需要查看设备的基线版本号,查询此基线版本是否支持文件管理的异步调用方式。
2、fileio模块无复制文件夹方法
fileio模块提供了文件的复制,但是没有文件夹的复制,因此在实现文件夹复制时,可能需要自行去遍历文件夹中的内容,逐个去遍历其中的文件并复制到相应位置,新建同名文件夹到相应位置。
3、文件夹删除时里面不能存在内容
fileio.rmdir删除文件夹时,文件夹中不能存在文件、文件夹数据,只有当文件夹为空时才可以删除文件夹。所以在删除文件夹时需先删除文件夹中的所有内容,再删除文件夹 。
fileio.rmdir(path)
.then(function(res) {
// 删除目录成功,do something
console.log('rmdir res: '+JSON.stringify(res))
}).catch(function(err){
console.log('rmdir err: '+JSON.stringify(err))
});
文件夹中没有文件数据执行删除文件夹返回:
文件夹中存在文件数据执行删除文件夹返回:
4、文件夹和文件移动
fileio模块中没有特定说明文件夹和文件的移动该如何实现,但我们可以通过 fileio.rename 重命名文件来实现,因为重命名文件需传入两个地址,一个是目标文件的当前绝对路径,一个是目标文件的新绝对路径,可以通过改变新绝对路径来实现文件夹和文件的移动。
// 若文件夹存放路径为:
let storagePath = 'res/data/data/com.kaihong.bookrack/files/storage/test';
// 需要移动到的路径为:
let movePath = 'res/data/data/com.kaihong.bookrack/files/move';
// 将文件存放路径后段拼接移动到的路径
let Newpath = movePath + '/test'
fileio.rename(storagePath, Newpath)
.then(function(res) {
// 重命名文件成功,do something
}).catch(function(err){
});
本次分享的内容是基于在文件管理模块中发现的部分问题记录,希望和大家一起成长。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK