介绍
HarmonyOS的沙盒机制完全屏蔽了应用对手机公共存储空间的访问,安全性提高已不言而喻。 本篇文章的主要目的是为了能通过一个简单工具,可视化的让一个新手能相对轻松的学习文件&数据存储。HarmonyOS 应用开发工具DevEco Studio也没有提供读取存储器的功能,所以做一个简单版本的应用级别浏览器还是有必要的。
准备
- 请参照官方指导,创建一个Demo工程,选择Stage模型
- 熟读HarmonyOS 官方指导“文件管理”
效果
页面由三部分组成:1.标题栏(用于返回)2. 当前路径描述 3. 文件列表
应用文件目录结构图
如果之前你熟悉Android存储目录,在学习HarmonyOS时,可以忘记之前所有了的东西了,因为HarmonyOS真的能让研发人员感受沙盒的存在,这点可以对标iOS系统
代码片段解析
1)获取个人应用沙盒下的所有根目录
this.context.bundleCodeDir
this.context.cacheDir
this.context.filesDir
this.context.preferencesDir
this.context.tempDir
this.context.databaseDir
this.context.distributedFilesDir
2)遍历目录
import fs from '@ohos.file.fs';
//遍历 this.currentRoot 路径下的所有文件和文件夹
fs.listFile(this.currentRoot)
3)文件/文件夹类型判断
try {
stat = fs.statSync(tempPath)
} catch (e) {
//路径可能不存在
return
}
//判断是否为文件夹
stat.isDirectory()
//判断是否为文件
stat.isFile()
核心文件
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { CommonConstants } from '../common/CommonConstants';
import FileManagerStructModel from '../viewmodel/FileManagerStruct';
import { Title } from '../view/Title';
import router from '@ohos.router';
/**
* 官方指导
* https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/application-context-stage-0000001427744560-V3#ZH-CN_TOPIC_0000001574128741__%E8%8E%B7%E5%8F%96%E5%BA%94%E7%94%A8%E5%BC%80%E5%8F%91%E8%B7%AF%E5%BE%84
*
*/
@Entry
@Component
struct FileManagerIndex {
private context = getContext(this) as common.UIAbilityContext;
//当前路径下的文件和文件夹
@State listData: FileManagerStructModel[] = []
@State filePaths: string[] = []
@State childFilePaths: string[] = []
@State currentRoot: string = ''
pathLevel: number = 0
@State pathTips: string = ''
scroller: Scroller = new Scroller();
initItem(item){
let model = new FileManagerStructModel()
model.currentDirName