鸿蒙开发进阶(HarmonyOS )通过 ArkTS 接口获取并访问公共目录
鸿蒙NEXT开发实战往期必看文章:一分钟了解”纯血版!鸿蒙HarmonyOS Next应用开发!
“非常详细的” 鸿蒙HarmonyOS Next应用开发学习门路!(从零基础入门到精通)
HarmonyOS NEXT应用开发案例实践总结合(一连更新......)
HarmonyOS NEXT应用开发性能优化实践总结(一连更新......)
通过 ArkTS 接口获取并访问公共目录
目录环境能力接口(ohos.file.environment)提供获取公共目录路径的能力,支持三方应用在公共文件用户目录下进行文件访问操作。
束缚限制
[*]使用此方式,需确认装备具有以下体系能力:SystemCapability.FileManagement.File.Environment.FolderObtain,当前仅支持2in1装备。 if (!canIUse('SystemCapability.FileManagement.File.Environment.FolderObtain')) {
console.error('this api is not supported on this device');
return;
}
[*]公共目录获取接口仅用于获取公共目录路径,不对公共目录访问权限进行校验。若需访问公共目录需申请对应的公共目录访问权限。三方应用需要访问公共目录时,需通过弹窗授权向用户申请授予 Download 目录权限、Documents 目录权限或 Desktop 目录权限,具体参考访问控制-向用户申请授权。
"requestPermissions" : [
"ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY",
"ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY",
] 示例
[*] 获取公共目录路径。
import { BusinessError } from '@kit.BasicServicesKit';
import { Environment } from '@kit.CoreFileKit';
function getUserDirExample() {
try {
const downloadPath = Environment.getUserDownloadDir();
console.info(`success to getUserDownloadDir: ${downloadPath}`);
const documentsPath = Environment.getUserDocumentDir();
console.info(`success to getUserDocumentDir: ${documentsPath}`);
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`failed to get user dir, because: ${JSON.stringify(err)}`);
}
}
[*] 以 Download 目录为例,访问 Download 目录下的文件。
import { BusinessError } from '@kit.BasicServicesKit';
import { Environment } from '@kit.CoreFileKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
function readUserDownloadDirExample() {
// 检查是否具有 READ_WRITE_DOWNLOAD_DIRECTORY 权限,无权限则需要向用户申请授予权限。
try {
// 获取 Download 目录
const downloadPath = Environment.getUserDownloadDir();
console.info(`success to getUserDownloadDir: ${downloadPath}`);
const context = getContext() as common.UIAbilityContext;
const dirPath = context.filesDir;
console.info(`success to get filesDir: ${dirPath}`);
// 查看 Download 目录下的文件并拷贝到沙箱目录中
let fileList: string[] = fs.listFileSync(downloadPath);
fileList.forEach((file, index) => {
console.info(`${downloadPath} ${index}: ${file}`);
fs.copyFileSync(`${downloadPath}/${file}`, `${dirPath}/${file}`);
});
// 查看沙箱目录下对应的文件
fileList = fs.listFileSync(dirPath);
fileList.forEach((file, index) => {
console.info(`${dirPath} ${index}: ${file}`);
});
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`Error code: ${err.code}, message: ${err.message}`);
}
}
[*] 以 Download 目录为例,生存文件到 Download 目录。
import { BusinessError } from '@kit.BasicServicesKit';
import { Environment } from '@kit.CoreFileKit';
import { fileIo as fs } from '@kit.CoreFileKit';
function writeUserDownloadDirExample() {
// 检查是否具有 READ_WRITE_DOWNLOAD_DIRECTORY 权限,无权限则需要向用户申请授予权限。
try {
// 获取 Download 目录
const downloadPath = Environment.getUserDownloadDir();
console.info(`success to getUserDownloadDir: ${downloadPath}`);
// 保存 temp.txt 到 Download 目录下
const file = fs.openSync(`${downloadPath}/temp.txt`, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
fs.writeSync(file.fd, 'write a message');
fs.closeSync(file);
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`Error code: ${err.code}, message: ${err.message}`);
}
}
通过 C/C++ 接口获取并使用公共目录
除了通过 ArkTS 访问公共目录的方式,也可通过 C/C++ 接口进行目录访问,具体可以参考 Environment。
束缚限制
[*]使用此接口,需确认装备具有以下体系能力:SystemCapability.FileManagement.File.Environment.FolderObtain。
[*]三方应用需要访问公共目录时,需通过弹窗授权向用户申请授予 Download 目录权限、Documents 目录权限或 Desktop 目录权限,具体参考访问控制-向用户申请授权。
接口说明
接口的详细说明,请参考API参考
接口名称形貌FileManagement_ErrCode OH_Environment_GetUserDownloadDir (char **result)获取用户Download目录沙箱路径。只支持2in1装备FileManagement_ErrCode OH_Environment_GetUserDesktopDir (char **result)获取用户Desktop目录沙箱路径。只支持2in1装备FileManagement_ErrCode OH_Environment_GetUserDocumentDir (char **result)获取用户Document目录沙箱路径。只支持2in1装备 开发步骤
在CMake脚本中链接动态库
CMakeLists.txt中添加以下lib。
target_link_libraries(sample PUBLIC libohenvironment.so libhilog_ndk.z.so) 添加头文件
#include <filemanagement/environment/oh_environment.h>
#include <filemanagement/fileio/oh_fileio.h>
#include <hilog/log.h>
[*] 调用 OH_Environment_GetUserDownloadDir 接口获取用户 Download 目录沙箱路径,在接口中使用malloc申请的内存需要在使用完后开释因此需要free对应的内存。示例代码如下所示:
void GetUserDownloadDirExample()
{
char *downloadPath = nullptr;
FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath);
if (ret == 0) {
OH_LOG_INFO(LOG_APP, "Download Path=%{public}s", downloadPath);
free(downloadPath);
} else {
OH_LOG_ERROR(LOG_APP, "GetDownloadPath fail, error code is %{public}d", ret);
}
}
[*] 调用 OH_Environment_GetUserDownloadDir 接口获取用户 Download 目录沙箱路径,并查看 Download 目录下的文件。示例代码如下所示:
void ScanUserDownloadDirPathExample()
{
// 获取 download 路径
char *downloadPath = nullptr;
FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath);
if (ret == 0) {
OH_LOG_INFO(LOG_APP, "Download Path=%{public}s", downloadPath);
} else {
OH_LOG_ERROR(LOG_APP, "GetDownloadPath fail, error code is %{public}d", ret);
return;
}
// 查看文件夹下的文件
struct dirent **namelist = {nullptr};
int num = scandir(downloadPath, &namelist, nullptr, nullptr);
if (num < 0) {
free(downloadPath);
OH_LOG_ERROR(LOG_APP, "Failed to scan dir");
return;
}
for (int i = 0; i < num; i++) {
OH_LOG_INFO(LOG_APP, "%{public}s", namelist->d_name);
}
free(downloadPath);
free(namelist);
}
[*] 调用 OH_Environment_GetUserDownloadDir 接口获取用户 Download 目录沙箱路径,并生存 temp.txt 到 Download 目录下。示例代码如下所示:
void WriteUserDownloadDirPathExample()
{
// 获取 download 路径
char *downloadPath = nullptr;
FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath);
if (ret == 0) {
OH_LOG_INFO(LOG_APP, "Download Path=%{public}s", downloadPath);
} else {
OH_LOG_ERROR(LOG_APP, "GetDownloadPath fail, error code is %{public}d", ret);
return;
}
// 保存文件到 download 目录下
std::string filePath = std::string(downloadPath) + "/temp.txt";
free(downloadPath);
std::ofstream outfile;
outfile.open(filePath.c_str());
if (!outfile) {
OH_LOG_ERROR(LOG_APP, "Failed to open file");
return;
}
std::string msg = "Write a message";
outfile.write(msg.c_str(), sizeof(msg));
outfile.close();
}
https://i-blog.csdnimg.cn/direct/ba7d889920f34dc88b9611853b5806d2.png
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]