当前位置: 首页 > news >正文

【鸿蒙在 ETS (Extendable TypeScript) 中创建多级目录或文件,可以使用鸿蒙的文件系统 API】

鸿蒙在 ETS (Extendable TypeScript) 中创建多级目录或文件,可以使用鸿蒙的文件系统 API。

// 导入需要的模块
import fs from '@ohos.file.fs';const TAG="Index"
@Entry
@Component
struct Index {@State message: string = 'Hello World';build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Button("创建目录").margin({ top: 10 }).onClick(() => {// 调用示例this.createDirsByRelativePath('path/to/your/dir');})Button("创建文件").margin({ top: 10 }).onClick(() => {// 调用示例this.createFile('path/to/your/dir/a.txt');})}.width('100%')}.height('100%')}/*** 创建文件* @param featurePath*/async createFile(featurePath:string){let mFeaturePath = "";if (featurePath.indexOf("/") != -1) {//创建目录let lastAIndex = featurePath.lastIndexOf('/');let fFileDir: string = featurePath.slice(0, lastAIndex);let fileName: string = featurePath.slice(lastAIndex + 1);console.info(TAG, "arrPath:" + fFileDir);if (fFileDir.length != 0) {await this.createDirsByRelativePath(fFileDir);mFeaturePath = getContext(this).filesDir + fFileDir + "/" + fileName;} else {mFeaturePath = getContext(this).filesDir + "/" + fileName;}} else {mFeaturePath = getContext(this).filesDir + "/" + featurePath;}console.info(TAG, "mFeaturePath:" + mFeaturePath);}// 递归创建目录async createMultiDirs(dirPath: string): Promise<void> {try {// 先检查目录是否存在let isExist = await fs.access(dirPath);if (isExist) {console.info(`Directory already exists: ${dirPath}`);return;}} catch (err) {// 如果目录不存在,则继续创建}// 获取父目录const parentDir = dirPath.substring(0, dirPath.lastIndexOf('/'));// 如果父目录不是根目录,且父目录不存在,则递归创建父目录if (parentDir && parentDir !== '/' && parentDir !== '') {try {// 检查父目录是否存在,如果不存在则递归创建await this.createMultiDirs(parentDir);} catch (err) {console.error(`Failed to create parent directory: ${parentDir}, error: ${JSON.stringify(err)}`);}}// 创建当前目录try {await fs.mkdir(dirPath);console.info(`Directory created: ${dirPath}`);} catch (err) {// 如果错误码为13900015(文件已存在),则忽略,否则抛出错误if (err.code !== 13900015) {console.error(`Failed to create directory: ${dirPath}, error: ${JSON.stringify(err)}`);}}}// 创建相对路径的多级目录(入口函数)async createDirsByRelativePath(relativePath: string): Promise<void> {const context = getContext();const baseDir = context.filesDir;const targetDir = baseDir + '/' + relativePath;try {await this.createMultiDirs(targetDir);console.info('All directories created successfully.');} catch (err) {console.error(`Failed to create directories: ${JSON.stringify(err)}`);}}// 创建多级目录async createDirs(basePath: string, relativePath: string): Promise<boolean> {const fullPath = basePath + '/' + relativePath;try {await fs.mkdir(fullPath);console.info(`目录创建成功: ${fullPath}`);return true;} catch (error) {console.error(`目录创建失败: ${JSON.stringify(error)}`);return false;}}// 创建文件(带路径自动创建)async createFileWithPath(basePath: string, filePath: string, content: string = ''): Promise<boolean> {const fullPath = basePath + '/' + filePath;try {// 分离目录路径和文件名const lastSlashIndex = filePath.lastIndexOf('/');const dirPath = lastSlashIndex > 0 ? filePath.substring(0, lastSlashIndex) : '';// 创建目录(如果目录路径存在)if (dirPath) {await this.createDirs(basePath, dirPath);}// 创建文件并写入内容const file = await fs.open(fullPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);if (content) {await fs.write(file.fd, content);}await fs.close(file.fd);console.info(`文件创建成功: ${fullPath}`);return true;} catch (error) {console.error(`文件创建失败: ${JSON.stringify(error)}`);return false;}}// 检查文件是否存在async fileExists(basePath: string, filePath: string): Promise<boolean> {const fullPath = basePath + '/' + filePath;try {await fs.access(fullPath);return true;} catch {return false;}}
}

相关文章:

  • 力扣刷题Day 71:搜索旋转排序数组(33)
  • Win10、Win11系统,使用谷歌浏览器文件流下载,C盘剩余容量小于4GB时,下载失败问题
  • 我的创作纪念日——聊聊我想成为一个创作者的动机
  • 25.6.5学习总结
  • 风机下引线断点检测算法实现
  • 系统思考持续训练
  • 【Redis】笔记|第10节|京东HotKey实现多级缓存架构
  • 简化复杂系统的优雅之道:深入解析 Java 外观模式
  • AI大模型在测试领域应用案例拆解:AI赋能的软件测试效能跃迁的四大核心引擎(顺丰科技)
  • Q: 数据库增删改查的逻辑如何实现?
  • 软件测试基础知识总结
  • 08_10小结
  • 八:操作系统设备管理之磁盘调度算法
  • 前端面试题之浏览器存储技术Cookie、LocalStorage、SessionStorage、indexDB
  • [蓝桥杯]后缀表达式
  • Scrum基础知识以及Scrum和传统瀑布式开发的区别
  • STL优先级队列的比较函数与大堆小堆的关系
  • I.MX6ULL裸机的EPIT实验
  • 贪心,回溯,动态规划
  • 从零发布一个 Vue 3 Button 组件到 npm(基于 Vite)
  • 家乡网络推广方案/宁波seo网站
  • 网站开发教学/手机建站平台
  • 做外贸需要关注的网站有什么问题/seo综合优化公司
  • 怎样装修公司网站/google chrome谷歌浏览器
  • web2.0网站开发d/南昌seo优化公司
  • 贵阳做网站公司/下载官方正版百度