1# 获取并使用公共目录 2 3## 通过 ArkTS 接口获取并访问公共目录 4 5目录环境能力接口([ohos.file.environment](../reference/apis-core-file-kit/js-apis-file-environment.md))提供获取公共目录路径的能力,支持三方应用在公共文件用户目录下进行文件访问操作。 6 7 **约束限制** 8 - 使用此方式,需确认设备具有以下系统能力:SystemCapability.FileManagement.File.Environment.FolderObtain,当前仅支持2in1设备。 9 ```ts 10 if (!canIUse('SystemCapability.FileManagement.File.Environment.FolderObtain')) { 11 console.error('this api is not supported on this device'); 12 return; 13 } 14 ``` 15 - 公共目录获取接口仅用于获取公共目录路径,不对公共目录访问权限进行校验。若需访问公共目录需申请对应的公共目录访问权限。三方应用需要访问公共目录时,需通过弹窗授权向用户申请授予 Download 目录权限、Documents 目录权限或 Desktop 目录权限,具体参考[访问控制-向用户申请授权](../security/AccessToken/request-user-authorization.md)。 16 <!--RP1--> 17 ```json 18 "requestPermissions" : [ 19 "ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY", 20 "ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY", 21 "ohos.permission.READ_WRITE_DESKTOP_DIRECTORY", 22 ] 23 ``` 24 <!--RP1End--> 25 26### 示例 27 281. 获取公共目录路径。 29 30 ```ts 31 import { BusinessError } from '@kit.BasicServicesKit'; 32 import { Environment } from '@kit.CoreFileKit'; 33 34 function getUserDirExample() { 35 try { 36 const downloadPath = Environment.getUserDownloadDir(); 37 console.info(`success to getUserDownloadDir: ${downloadPath}`); 38 const documentsPath = Environment.getUserDocumentDir(); 39 console.info(`success to getUserDocumentDir: ${documentsPath}`); 40 } catch (error) { 41 const err: BusinessError = error as BusinessError; 42 console.error(`failed to get user dir, because: ${JSON.stringify(err)}`); 43 } 44 } 45 ``` 46 472. 以 Download 目录为例,访问 Download 目录下的文件。 48 49 ```ts 50 import { BusinessError } from '@kit.BasicServicesKit'; 51 import { Environment } from '@kit.CoreFileKit'; 52 import { fileIo as fs } from '@kit.CoreFileKit'; 53 import { common } from '@kit.AbilityKit'; 54 55 function readUserDownloadDirExample() { 56 // 检查是否具有 READ_WRITE_DOWNLOAD_DIRECTORY 权限,无权限则需要向用户申请授予权限。 57 try { 58 // 获取 Download 目录 59 const downloadPath = Environment.getUserDownloadDir(); 60 console.info(`success to getUserDownloadDir: ${downloadPath}`); 61 const context = getContext() as common.UIAbilityContext; 62 const dirPath = context.filesDir; 63 console.info(`success to get filesDir: ${dirPath}`); 64 // 查看 Download 目录下的文件并拷贝到沙箱目录中 65 let fileList: string[] = fs.listFileSync(downloadPath); 66 fileList.forEach((file, index) => { 67 console.info(`${downloadPath} ${index}: ${file}`); 68 fs.copyFileSync(`${downloadPath}/${file}`, `${dirPath}/${file}`); 69 }); 70 // 查看沙箱目录下对应的文件 71 fileList = fs.listFileSync(dirPath); 72 fileList.forEach((file, index) => { 73 console.info(`${dirPath} ${index}: ${file}`); 74 }); 75 } catch (error) { 76 const err: BusinessError = error as BusinessError; 77 console.error(`Error code: ${err.code}, message: ${err.message}`); 78 } 79 } 80 ``` 81 823. 以 Download 目录为例,保存文件到 Download 目录。 83 84 ```ts 85 import { BusinessError } from '@kit.BasicServicesKit'; 86 import { Environment } from '@kit.CoreFileKit'; 87 import { fileIo as fs } from '@kit.CoreFileKit'; 88 89 function writeUserDownloadDirExample() { 90 // 检查是否具有 READ_WRITE_DOWNLOAD_DIRECTORY 权限,无权限则需要向用户申请授予权限。 91 try { 92 // 获取 Download 目录 93 const downloadPath = Environment.getUserDownloadDir(); 94 console.info(`success to getUserDownloadDir: ${downloadPath}`); 95 // 保存 temp.txt 到 Download 目录下 96 const file = fs.openSync(`${downloadPath}/temp.txt`, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 97 fs.writeSync(file.fd, 'write a message'); 98 fs.closeSync(file); 99 } catch (error) { 100 const err: BusinessError = error as BusinessError; 101 console.error(`Error code: ${err.code}, message: ${err.message}`); 102 } 103 } 104 ``` 105 106 107 108## 通过 C/C++ 接口获取并使用公共目录 109 110除了通过 ArkTS 访问公共目录的方式,也可通过 C/C++ 接口进行目录访问,具体可以参考 [Environment](../reference/apis-core-file-kit/_environment.md)。 111 112 **约束限制** 113 - 使用此接口,需确认设备具有以下系统能力:SystemCapability.FileManagement.File.Environment.FolderObtain。 114 - 三方应用需要访问公共目录时,需通过弹窗授权向用户申请授予 Download 目录权限、Documents 目录权限或 Desktop 目录权限,具体参考[访问控制-向用户申请授权](../security/AccessToken/request-user-authorization.md)。 115 116### 接口说明 117 118接口的详细说明,请参考[API参考](../reference/apis-core-file-kit/_environment.md) 119 120| 接口名称 | 描述 | 121| ------------------------------------------------------------------------ | ------------------------------ | 122| FileManagement_ErrCode OH_Environment_GetUserDownloadDir (char **result) | 获取用户Download目录沙箱路径。只支持2in1设备 | 123| FileManagement_ErrCode OH_Environment_GetUserDesktopDir (char **result) | 获取用户Desktop目录沙箱路径。只支持2in1设备 | 124| FileManagement_ErrCode OH_Environment_GetUserDocumentDir (char **result) | 获取用户Document目录沙箱路径。只支持2in1设备 | 125 126### 开发步骤 127 128**在CMake脚本中链接动态库** 129 130CMakeLists.txt中添加以下lib。 131 132```txt 133target_link_libraries(sample PUBLIC libohenvironment.so libhilog_ndk.z.so) 134``` 135 136**添加头文件** 137 138```c++ 139#include <filemanagement/environment/oh_environment.h> 140#include <filemanagement/fileio/oh_fileio.h> 141#include <hilog/log.h> 142``` 143 1441. 调用 OH_Environment_GetUserDownloadDir 接口获取用户 Download 目录沙箱路径,在接口中使用malloc申请的内存需要在使用完后释放因此需要free对应的内存。示例代码如下所示: 145 146 ```c++ 147 void GetUserDownloadDirExample() 148 { 149 char *downloadPath = nullptr; 150 FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath); 151 if (ret == 0) { 152 OH_LOG_INFO(LOG_APP, "Download Path=%{public}s", downloadPath); 153 free(downloadPath); 154 } else { 155 OH_LOG_ERROR(LOG_APP, "GetDownloadPath fail, error code is %{public}d", ret); 156 } 157 } 158 ``` 159 1602. 调用 OH_Environment_GetUserDownloadDir 接口获取用户 Download 目录沙箱路径,并查看 Download 目录下的文件。示例代码如下所示: 161 162 ```c++ 163 void ScanUserDownloadDirPathExample() 164 { 165 // 获取 download 路径 166 char *downloadPath = nullptr; 167 FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath); 168 if (ret == 0) { 169 OH_LOG_INFO(LOG_APP, "Download Path=%{public}s", downloadPath); 170 } else { 171 OH_LOG_ERROR(LOG_APP, "GetDownloadPath fail, error code is %{public}d", ret); 172 return; 173 } 174 // 查看文件夹下的文件 175 struct dirent **namelist = {nullptr}; 176 int num = scandir(downloadPath, &namelist, nullptr, nullptr); 177 if (num < 0) { 178 free(downloadPath); 179 OH_LOG_ERROR(LOG_APP, "Failed to scan dir"); 180 return; 181 } 182 for (int i = 0; i < num; i++) { 183 OH_LOG_INFO(LOG_APP, "%{public}s", namelist[i]->d_name); 184 } 185 free(downloadPath); 186 free(namelist); 187 } 188 ``` 189 1903. 调用 OH_Environment_GetUserDownloadDir 接口获取用户 Download 目录沙箱路径,并保存 temp.txt 到 Download 目录下。示例代码如下所示: 191 192 ```c++ 193 void WriteUserDownloadDirPathExample() 194 { 195 // 获取 download 路径 196 char *downloadPath = nullptr; 197 FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath); 198 if (ret == 0) { 199 OH_LOG_INFO(LOG_APP, "Download Path=%{public}s", downloadPath); 200 } else { 201 OH_LOG_ERROR(LOG_APP, "GetDownloadPath fail, error code is %{public}d", ret); 202 return; 203 } 204 // 保存文件到 download 目录下 205 std::string filePath = std::string(downloadPath) + "/temp.txt"; 206 free(downloadPath); 207 208 std::ofstream outfile; 209 outfile.open(filePath.c_str()); 210 if (!outfile) { 211 OH_LOG_ERROR(LOG_APP, "Failed to open file"); 212 return; 213 } 214 std::string msg = "Write a message"; 215 outfile.write(msg.c_str(), sizeof(msg)); 216 outfile.close(); 217 } 218 ``` 219