首页 文章 精选 留言 我的

精选列表

搜索[鸿蒙App],共10000篇文章
优秀的个人博客,低调大师

拥抱原生智能:AI + 鸿蒙应用开发从零到商用落地指南

HarmonyOS NEXT 的 AI 不是"外挂 SDK",而是端云协同 + 系统级分发的原生能力。端侧有 Core Vision Kit、Core Speech Kit、Natural Language Kit、MindSpore Lite;云侧有 Intelligent Cloud;分发层是意图框架 Intents Kit。商用应用的选型原则是:隐私敏感、低时延、需离线 → 端侧;大模型推理、复杂生成 → 云侧;能力被小艺调用 → 意图框架。

优秀的个人博客,低调大师

鸿蒙 文件管理与沙箱访问实战:读写、权限与跨端同步

## 为什么要懂沙箱文件管理 在 HarmonyOS 应用中,文件操作几乎是刚需:用户文档、缓存图片、下载的 PDF、录音文件……如果不清楚沙箱边界、目录结构和权限模型,极易踩坑:存错目录导致卸载后数据丢失、跨应用共享失败、或因权限不足崩溃。 本文聚焦 HarmonyOS 文件管理的核心场景: - 应用沙箱的目录结构与生命周期 - 内部文件读写(cache / files / temp / preferences) - 用户文档访问(公共目录、Picker、DocumentsProvider) - 文件权限申请与持久化授权 - 跨设备文件同步(分布式文件服务) - 实战封装:统一文件管理器 ## 沙箱目录结构与生命周期 HarmonyOS 应用运行在沙箱环境中,每个应用拥有独立的文件空间。Stage 模型下,常用目录包括: - **cache/** — 缓存目录,系统可随时清理,适合临时文件(图片缓存、网络响应) - **files/** — 应用私有数据,卸载后删除,适合配置文件、用户生成内容 - **temp/** — 临时目录,应用退出后可能被清理 - **preferences/** — 轻量级键值存储目录(由 Preferences API 管理) - **database/** — 关系型数据库目录(由 relationalStore 管理) ### 获取沙箱路径 ``` import { common } from '@kit.AbilityKit'; @Entry @Component struct FilePathDemo { @State cacheDir: string = ''; @State filesDir: string = ''; @State tempDir: string = ''; aboutToAppear() { const context = getContext(this) as common.UIAbilityContext; this.cacheDir = context.cacheDir; // /data/storage/el2/base/cache this.filesDir = context.filesDir; // /data/storage/el2/base/files this.tempDir = context.tempDir; // /data/storage/el2/base/temp } build() { Column({ space: 12 }) { Text(`Cache: ${this.cacheDir}`) Text(`Files: ${this.filesDir}`) Text(`Temp: ${this.tempDir}`) }.padding(20) } } ``` ## 内部文件读写:基于 fs 模块 HarmonyOS 提供 `@ohos.file.fs` 模块进行同步/异步文件操作,API 风格类似 Node.js。 ### 写入文本文件 ``` import { fileIo as fs } from '@kit.CoreFileKit'; import { common } from '@kit.AbilityKit'; async function writeTextFile(fileName: string, content: string) { const context = getContext() as common.UIAbilityContext; const filePath = `${context.filesDir}/${fileName}`; try { const file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.WRITE_ONLY); fs.writeSync(file.fd, content); fs.closeSync(file.fd); console.info(`文件已写入: ${filePath}`); } catch (err) { console.error(`写入失败: ${err.message}`); } } // 使用 writeTextFile('user_notes.txt', '这是用户笔记内容'); ``` ### 读取文本文件 ``` async function readTextFile(fileName: string): Promise { const context = getContext() as common.UIAbilityContext; const filePath = `${context.filesDir}/${fileName}`; try { const file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); const stat = fs.statSync(filePath); const buffer = new ArrayBuffer(stat.size); fs.readSync(file.fd, buffer); fs.closeSync(file.fd); const decoder = new util.TextDecoder('utf-8'); return decoder.decodeWithStream(new Uint8Array(buffer)); } catch (err) { console.error(`读取失败: ${err.message}`); return ''; } } ``` ### 文件复制与删除 ``` // 复制文件 fs.copyFileSync(srcPath, destPath); // 删除文件 fs.unlinkSync(filePath); // 检查文件是否存在 const exists = fs.accessSync(filePath); ``` ## 访问用户公共目录:Picker 与权限 若需访问用户的照片、文档、下载文件等公共目录,必须通过 **Picker**(文件选择器)或申请 `ohos.permission.READ_MEDIA` 等权限。 ### 使用 DocumentViewPicker 选择文件 ``` import { picker } from '@kit.CoreFileKit'; async function pickDocument(): Promise { try { const documentPicker = new picker.DocumentViewPicker(); const result = await documentPicker.select({ maxSelectNumber: 1 }); if (result && result.length > 0) { const uri = result[0]; console.info(`选中文件 URI: ${uri}`); return uri; } } catch (err) { console.error(`选择文件失败: ${err.message}`); } return ''; } ``` ### 申请媒体文件读取权限 若需批量访问或后台访问用户文件,需在 `module.json5` 中声明权限: ``` { "requestPermissions": [ { "name": "ohos.permission.READ_MEDIA", "reason": "$string:media_read_reason", "usedScene": { "abilities": ["EntryAbility"], "when": "inuse" } } ] } ``` 运行时动态申请: ``` import { abilityAccessCtrl, common } from '@kit.AbilityKit'; async function requestMediaPermission() { const context = getContext() as common.UIAbilityContext; const atManager = abilityAccessCtrl.createAtManager(); try { const result = await atManager.requestPermissionsFromUser(context, ['ohos.permission.READ_MEDIA']); if (result.authResults[0] === 0) { console.info('媒体读取权限已授予'); return true; } } catch (err) { console.error(`权限申请失败: ${err.message}`); } return false; } ``` ## 跨设备文件同步:分布式文件服务 HarmonyOS 支持分布式文件能力,允许应用在多设备间共享文件(如手机 ↔ 平板、PC)。核心 API 位于 `@ohos.file.distributedFile`。 ### 开启分布式文件访问 ``` import { distributedFile } from '@kit.CoreFileKit'; async function enableDistributedFile(deviceId: string, fileName: string) { try { const remotePath = `${deviceId}/data/storage/el2/base/files/${fileName}`; const localPath = `/data/storage/el2/distributedfiles/${fileName}`; await distributedFile.access(remotePath); console.info(`远程文件可访问: ${remotePath}`); // 后续可通过 fs 模块读取 localPath(系统自动同步) } catch (err) { console.error(`分布式文件访问失败: ${err.message}`); } } ``` ## 实战封装:统一文件管理器 将常用操作封装为工具类,简化调用: ``` import { fileIo as fs } from '@kit.CoreFileKit'; import { common } from '@kit.AbilityKit'; export class FileManager { private static context: common.UIAbilityContext; static init(ctx: common.UIAbilityContext) { this.context = ctx; } // 写入文本到 files 目录 static async writeText(fileName: string, content: string): Promise { const filePath = `${this.context.filesDir}/${fileName}`; try { const file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.WRITE_ONLY); fs.writeSync(file.fd, content); fs.closeSync(file.fd); return true; } catch (err) { console.error(`FileManager.writeText 失败: ${err.message}`); return false; } } // 读取文本 static async readText(fileName: string): Promise { const filePath = `${this.context.filesDir}/${fileName}`; try { const file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); const stat = fs.statSync(filePath); const buffer = new ArrayBuffer(stat.size); fs.readSync(file.fd, buffer); fs.closeSync(file.fd); const decoder = new util.TextDecoder('utf-8'); return decoder.decodeWithStream(new Uint8Array(buffer)); } catch (err) { console.error(`FileManager.readText 失败: ${err.message}`); return ''; } } // 删除文件 static delete(fileName: string): boolean { const filePath = `${this.context.filesDir}/${fileName}`; try { fs.unlinkSync(filePath); return true; } catch (err) { console.error(`FileManager.delete 失败: ${err.message}`); return false; } } // 检查文件是否存在 static exists(fileName: string): boolean { const filePath = `${this.context.filesDir}/${fileName}`; try { return fs.accessSync(filePath); } catch { return false; } } // 清空 cache 目录 static clearCache(): boolean { try { const cacheDir = this.context.cacheDir; const files = fs.listFileSync(cacheDir); files.forEach(file => { fs.unlinkSync(`${cacheDir}/${file}`); }); return true; } catch (err) { console.error(`FileManager.clearCache 失败: ${err.message}`); return false; } } } ``` ### 使用示例 ``` // 初始化 FileManager.init(getContext(this) as common.UIAbilityContext); // 写入文件 await FileManager.writeText('config.json', JSON.stringify({ theme: 'dark' })); // 读取文件 const configText = await FileManager.readText('config.json'); const config = JSON.parse(configText); // 检查文件 if (FileManager.exists('user_data.txt')) { console.info('用户数据文件存在'); } // 清空缓存 FileManager.clearCache(); ``` ## 常见坑点与最佳实践 |坑点|表现|解决方案| | --- | --- | --- | |文件存到 cache 目录后找不到|系统清理缓存后文件丢失|重要数据存 files/,缓存仅用于可再生内容| |跨应用共享文件失败|无法通过文件路径直接访问|使用 Picker 或 ContentProvider 共享 URI| |文件路径包含中文导致读取失败|编码问题|使用 UTF-8 编码,避免特殊字符| |分布式文件同步延迟高|大文件同步慢|分块传输、压缩、或使用云存储中转| |权限申请后仍无法访问|权限声明不完整|检查 module.json5 和运行时申请是否都完成| ## 总结 HarmonyOS 文件管理的核心是理解沙箱边界与权限模型: - **沙箱内**(cache / files / temp)— 自由读写,无需权限 - **用户公共目录** — 必须通过 Picker 或申请权限 - **跨设备同步** — 使用分布式文件服务,需分布式权限 封装统一的 FileManager 工具类,可显著降低文件操作的复杂度,提升代码可维护性。

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码