鸿蒙OS开发实例:【应用级别文件浏览器】

介绍

HarmonyOS的沙盒机制完全屏蔽了应用对手机公共存储空间的访问,安全性提高已不言而喻。 本篇文章的主要目的是为了能通过一个简单工具,可视化的让一个新手能相对轻松的学习文件&数据存储。HarmonyOS 应用开发工具DevEco Studio也没有提供读取存储器的功能,所以做一个简单版本的应用级别浏览器还是有必要的。

准备

  1. 请参照官方指导,创建一个Demo工程,选择Stage模型
  2. 须熟读HarmonyOS 指导"文件管理gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md"

效果

页面由三部分组成:1.标题栏(用于返回)2. 当前路径描述 3. 文件列表

应用文件目录结构图

如果之前你熟悉Android存储目录,在学习HarmonyOS时,可以忘记之前所有了的东西了,因为HarmonyOS真的能让研发人员感受沙盒的存在,这点可以对标iOS系统

代码片段解析

1)获取个人应用沙盒下的所有根目录

cpp 复制代码
this.context.bundleCodeDir
this.context.cacheDir
this.context.filesDir
this.context.preferencesDir
this.context.tempDir
this.context.databaseDir
this.context.distributedFilesDir

2)遍历目录

cpp 复制代码
import fs from '@ohos.file.fs';

//遍历 this.currentRoot 路径下的所有文件和文件夹
fs.listFile(this.currentRoot)

3)文件/文件夹类型判断

cpp 复制代码
try {
  stat = fs.statSync(tempPath)
} catch (e) {
  //路径可能不存在
  return
}

//判断是否为文件夹
stat.isDirectory()

//判断是否为文件
stat.isFile()

核心文件

cpp 复制代码
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 = item.substring(item.lastIndexOf('/')+1)
    model.currentPath = item.substring(0, item.lastIndexOf('/'))

    let stat

    try {
      stat = fs.statSync(item)
    } catch (e){
      console.log(e)
      return
    }

    if(fs.statSync(item).isDirectory()){
      model.isDir = true
      model.smallIMG = $r('app.media.ic_files_folder')
    } else {
      model.isDir = false
      if(item.toLowerCase().endsWith('.png')
        || item.toLowerCase().endsWith('.png')
        || item.toLowerCase().endsWith('.jpg')
        || item.toLowerCase().endsWith('.bmp')){
        model.smallIMG = $r('app.media.ic_files_image')
      } else  if(item.toLowerCase().endsWith('.doc')) {
        model.smallIMG = $r('app.media.ic_files_doc')
      } else  if(item.toLowerCase().endsWith('.log')) {
        model.smallIMG = $r('app.media.ic_files_log')
      } else  if(item.toLowerCase().endsWith('.html')) {
        model.smallIMG = $r('app.media.ic_files_html')
      } else  if(item.toLowerCase().endsWith('.pdf')) {
        model.smallIMG = $r('app.media.ic_files_pdf')
      } else  if(item.toLowerCase().endsWith('.xml')) {
        model.smallIMG = $r('app.media.ic_files_xml')
      } else  if(item.toLowerCase().endsWith('.txt')) {
        model.smallIMG = $r('app.media.ic_files_grid_txt')
      } else  if(item.toLowerCase().endsWith('.chm')) {
        model.smallIMG = $r('app.media.ic_files_chm')
      } else  if(item.toLowerCase().endsWith('.pptx')) {
        model.smallIMG = $r('app.media.ic_files_pptx')
      } else  if(item.toLowerCase().endsWith('.mp3')) {
        model.smallIMG = $r('app.media.ic_files_mp3')
      } else  if(item.toLowerCase().endsWith('.mp4')) {
        model.smallIMG = $r('app.media.ic_files_m4a')
      } else {
        model.smallIMG = $r('app.media.ic_files_unknown')
      }
    }

    this.listData.push(model)
  }

  initCurrentDir(){
    this.pathTips = '我的应用'

    this.listData = []
    this.filePaths.forEach((item)=>{
       this.initItem(item)
    })
  }

  aboutToAppear(){
    this.filePaths.push(this.context.bundleCodeDir)
    this.filePaths.push(this.context.cacheDir)
    this.filePaths.push(this.context.filesDir)
    this.filePaths.push(this.context.preferencesDir)
    this.filePaths.push(this.context.tempDir)
    this.filePaths.push(this.context.databaseDir)
    this.filePaths.push(this.context.distributedFilesDir)

    console.log(this.context.bundleCodeDir)
    console.log(this.context.cacheDir)
    console.log(this.context.filesDir)
    console.log(this.context.preferencesDir)
    console.log(this.context.tempDir)
    console.log(this.context.databaseDir)
    console.log(this.context.distributedFilesDir)

    this.initCurrentDir()

  }

  build(){
    Column(){
      Title({title: '返回'})
      .onClick(()=> {
        if (this.currentRoot != this.context.bundleCodeDir
        && this.currentRoot != this.context.cacheDir
        && this.currentRoot != this.context.filesDir
        && this.currentRoot != this.context.preferencesDir
        && this.currentRoot != this.context.tempDir
        && this.currentRoot != this.context.databaseDir
        && this.currentRoot != this.context.distributedFilesDir) {

          this.currentRoot = this.currentRoot.substring(0, this.currentRoot.lastIndexOf('/'))

          this.pathTips = this.pathTips.substring(0, this.pathTips.lastIndexOf('>'))

          this.pathLevel--
          fs.listFile(this.currentRoot)
            .then((filesPath: string[]) => {
              this.listData = []
              filesPath.forEach((info) => {
                this.initItem(this.currentRoot + '/' + info)
              })
            })

        } else {

          this.pathLevel--

          console.log('当前级数:' + this.pathLevel)

          if(this.pathLevel < 0){
            router.back()
            return
          } else {
            this.initCurrentDir()
          }

        }
      })
      .height('5%')

      Text(this.pathTips).fontSize(10).fontColor(Color.Gray).width('100%').margin({top: 10, bottom: 10})

      Stack(){
        if(this.listData == null || this.listData.length == 0){
          Text('空空如也')
            .width('100%')
            .height('100%')
            .fontSize(25)
            .textAlign(TextAlign.Center)
        } else {
          List(){
            ForEach(this.listData, (item: FileManagerStructModel, index: number) => {
              ListItem(){
                Row(){
                  Image(item.smallIMG).width(30).height(30).objectFit(ImageFit.Contain)
                  Text(item.currentDirName).margin({left: 10})
                }.width('100%').height(60).onClick(()=>{

                  let tempPath = item.currentPath + '/' + item.currentDirName
                  console.log(tempPath)

                  let stat

                  try {
                    stat = fs.statSync(tempPath)
                  } catch (e) {
                    console.log(e)
                    return
                  }

                  if(stat.isDirectory()){
                    this.currentRoot = tempPath

                    this.pathTips = this.pathTips + '>' + item.currentDirName;

                    this.pathLevel++

                    this.listData = []
                    fs.listFile(this.currentRoot)
                      .then( (filePaths: string[]) => {
                          filePaths.forEach((info)=>{
                            this.initItem(this.currentRoot+'/'+info)
                          }
                        )
                      })
                  }

                })
              }
            })
          }
          .width('100%')
          .height('100%')
        }
      }
      .width('100%')
      .height('94%')
    }
    .alignItems(HorizontalAlign.Start)
    .margin({top: 10})
    .padding({top: px2vp(AppStorage.Get(CommonConstants.StatusBarHeight)), left: '10vp', right: '10vp'})

  }

}

最后呢,很多开发朋友不知道需要学习那些鸿蒙技术?鸿蒙开发岗位需要掌握那些核心技术点?为此鸿蒙的开发学习必须要系统性的进行。

而网上有关鸿蒙的开发资料非常的少,假如你想学好鸿蒙的应用开发与系统底层开发。你可以参考这份资料,少走很多弯路,节省没必要的麻烦。由两位前阿里高级研发工程师联合打造 的**《鸿蒙NEXT星河版OpenHarmony开发文档》**里面内容包含了(**ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony****多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(Harmony NEXT)**技术知识点

如果你是一名Android、Java、前端等等开发人员,想要转入鸿蒙方向发展。可以直接领取这份资料辅助你的学习。下面是鸿蒙开发的学习路线图。

高清完整版请点击→《鸿蒙NEXT星河版开发学习文档》****

针对鸿蒙成长路线打造的鸿蒙学习文档。话不多说,我们直接看详细资料鸿蒙(OpenHarmony )学习手册(共计1236页)与鸿蒙(OpenHarmony )开发入门教学视频,帮助大家在技术的道路上更进一步。

《鸿蒙 (OpenHarmony)开发学习视频》

《鸿蒙生态应用开发V2.0白皮书》

《鸿蒙 (OpenHarmony)开发基础到实战手册》

获取这份鸿蒙星河版学习资料,请点击→ 《鸿蒙NEXT星河版开发学习文档》

OpenHarmony北向、南向开发环境搭建

《鸿蒙开发基础》

  1. ArkTS语言

  2. 安装DevEco Studio

  3. 运用你的第一个ArkTS应用

  4. ArkUI声明式UI开发

  5. .......

《鸿蒙开发进阶》

  1. Stage模型入门

  2. 网络管理

  3. 数据管理

  4. 电话服务

  5. 分布式应用开发

  6. 通知与窗口管理

  7. 多媒体技术

  8. 安全技能

  9. 任务管理

  10. WebGL

  11. 国际化开发

  12. 应用测试

  13. DFX面向未来设计

  14. 鸿蒙系统移植和裁剪定制

  15. ......

《鸿蒙开发实战》

  1. ArkTS实践

  2. UIAbility应用

  3. 网络案例

  4. ......

获取这份鸿蒙星河版学习资料,请点击→《鸿蒙NEXT星河版开发学习文档》

总结

鸿蒙---作为国家主力推送的国产操作系统。部分的高校已经取消了安卓课程,从而开设鸿蒙课程;企业纷纷跟进启动了鸿蒙研发

并且鸿蒙是完全具备无与伦比的机遇和潜力的;预计到年底将有 5,000 款的应用完成原生鸿蒙开发 ,未来将会支持 50 万款的应用那么这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才。鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行!

相关推荐
阿里嘎多学长5 小时前
2026-08-24 GitHub 热点项目精选
开发语言·程序员·github·代码托管
kyriewen6 小时前
我拿 4 个真实前端任务试了 GLM-5.3 Flash:代码一遍跑通,账单 4 分钱
前端·程序员·ai编程
Magic-ZYJ6 小时前
HarmonyOS Release 构建安全:ArkGuard 混淆、签名配置与秘密管理
安全·华为·harmonyos·移动应用开发·心晴手记
见山是山-见水是水7 小时前
拆解HarmonyOS网络请求适配:原生鸿蒙页面的实现路径与调试方法
华为·harmonyos
m0_749690237 小时前
【寻迹校园 HarmonyOS NEXT 实战 36】深色模式不是反色:用语义 Token 管理品牌色与状态色
harmonyos·arkts·深色模式·ui设计·主题设计
这个DBA有点耶8 小时前
MySQL主从延迟的“最后一公里”:如何把延迟压到极限
数据库·程序员·架构
lqj_本人8 小时前
鸿蒙跨端实战_QT后台切换导致OpenGLES上下文丢失:黑屏自救指南
qt·华为·harmonyos
OH_TPC10 小时前
HarmonyOS APP开发---“数据眼“健康追踪App,需要用到这个库
华为·harmonyos·鸿蒙
lilian23311 小时前
Harmony os 技术实战|拼豆制图49:五组分类视觉规则如何收口成一张配置表
华为·harmonyos
2501_9197490311 小时前
华为鸿蒙免费决策APP—小羊挠头
华为·harmonyos·鸿蒙