# 获å–并使用公共目录 ## 通过 ArkTS 接å£èŽ·å–并访问公共目录 目录环境能力接å£ï¼ˆ[ohos.file.environment](../reference/apis-core-file-kit/js-apis-file-environment.md))æä¾›èŽ·å–公共目录路径的能力,支æŒä¸‰æ–¹åº”用在公共文件用户目录下进行文件访问æ“作。 **约æŸé™åˆ¶** - ä½¿ç”¨æ¤æ–¹å¼ï¼Œéœ€ç¡®è®¤è®¾å¤‡å…·æœ‰ä»¥ä¸‹ç³»ç»Ÿèƒ½åŠ›ï¼šSystemCapability.FileManagement.File.Environment.FolderObtain,当å‰ä»…支æŒ2in1设备。 ```ts if (!canIUse('SystemCapability.FileManagement.File.Environment.FolderObtain')) { console.error('this api is not supported on this device'); return; } ``` - å…¬å…±ç›®å½•èŽ·å–æŽ¥å£ä»…用于获å–公共目录路径,ä¸å¯¹å…¬å…±ç›®å½•访问æƒé™è¿›è¡Œæ ¡éªŒã€‚若需访问公共目录需申请对应的公共目录访问æƒé™ã€‚三方应用需è¦è®¿é—®å…¬å…±ç›®å½•时,需通过弹窗授æƒå‘用户申请授予 Download 目录æƒé™ã€Documents 目录æƒé™æˆ– Desktop 目录æƒé™ï¼Œå…·ä½“å‚考[访问控制-å‘用户申请授æƒ](../security/AccessToken/request-user-authorization.md)。 <!--RP1--> ```json "requestPermissions" : [ "ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY", "ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY", "ohos.permission.READ_WRITE_DESKTOP_DIRECTORY", ] ``` <!--RP1End--> ### 示例 1. 获å–公共目录路径。 ```ts 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)}`); } } ``` 2. 以 Download 目录为例,访问 Download 目录下的文件。 ```ts 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}`); } } ``` 3. 以 Download 目录为例,ä¿å˜æ–‡ä»¶åˆ° Download 目录。 ```ts 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](../reference/apis-core-file-kit/_environment.md)。 **约æŸé™åˆ¶** - ä½¿ç”¨æ¤æŽ¥å£ï¼Œéœ€ç¡®è®¤è®¾å¤‡å…·æœ‰ä»¥ä¸‹ç³»ç»Ÿèƒ½åŠ›ï¼šSystemCapability.FileManagement.File.Environment.FolderObtain。 - 三方应用需è¦è®¿é—®å…¬å…±ç›®å½•时,需通过弹窗授æƒå‘用户申请授予 Download 目录æƒé™ã€Documents 目录æƒé™æˆ– Desktop 目录æƒé™ï¼Œå…·ä½“å‚考[访问控制-å‘用户申请授æƒ](../security/AccessToken/request-user-authorization.md)。 ### 接å£è¯´æ˜Ž 接å£çš„详细说明,请å‚考[APIå‚考](../reference/apis-core-file-kit/_environment.md) | 接å£åç§° | æè¿° | | ------------------------------------------------------------------------ | ------------------------------ | | 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。 ```txt target_link_libraries(sample PUBLIC libohenvironment.so libhilog_ndk.z.so) ``` **æ·»åŠ å¤´æ–‡ä»¶** ```c++ #include <filemanagement/environment/oh_environment.h> #include <filemanagement/fileio/oh_fileio.h> #include <hilog/log.h> ``` 1. 调用 OH_Environment_GetUserDownloadDir 接å£èŽ·å–用户 Download 目录沙箱路径,在接å£ä¸ä½¿ç”¨malloc申请的内å˜éœ€è¦åœ¨ä½¿ç”¨å®ŒåŽé‡Šæ”¾å› æ¤éœ€è¦free对应的内å˜ã€‚示例代ç 如下所示: ```c++ 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); } } ``` 2. 调用 OH_Environment_GetUserDownloadDir 接å£èŽ·å–用户 Download 目录沙箱路径,并查看 Download 目录下的文件。示例代ç 如下所示: ```c++ 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[i]->d_name); } free(downloadPath); free(namelist); } ``` 3. 调用 OH_Environment_GetUserDownloadDir 接å£èŽ·å–用户 Download 目录沙箱路径,并ä¿å˜ temp.txt 到 Download 目录下。示例代ç 如下所示: ```c++ 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(); } ```