鸿蒙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 万款的应用那么这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才。鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行!

相关推荐
xiezhr17 分钟前
近期提高幸福感的工具分享
程序员
爱海贼的无处不在1 小时前
一个需求竟然要开14个会:程序员的日常到底有多“会”?
后端·程序员
程序员潘Sir3 小时前
鸿蒙应用开发从入门到实战(六):ArkTS声明式UI和组件化
harmonyos·鸿蒙
白帽黑客沐瑶4 小时前
【网络安全就业】信息安全专业的就业前景(非常详细)零基础入门到精通,收藏这篇就够了
网络·安全·web安全·计算机·程序员·编程·网络安全就业
SimonKing4 小时前
【工具库推荐】Java开发者必备:6款HTTP客户端神器,从经典到未来
java·后端·程序员
猫林老师4 小时前
HarmonyOS数据持久化:Preferences轻量级存储实战
华为·harmonyos
这里有鱼汤5 小时前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员
Devil枫8 小时前
鸿蒙深链落地实战:从安全解析到异常兜底的全链路设计
安全·华为·harmonyos
野生的码农15 小时前
如何知道同事的工资?
程序员