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

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

c 复制代码
// 导入需要的模块
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;
    }
  }
}
相关推荐
ShiMetaPi4 小时前
ShimetaPi M4-R1:国产高性能嵌入式平台的异构计算架构与OpenHarmony生态实践
架构·视觉检测·边缘计算·鸿蒙·树莓派4·#rk3568·树莓派替代方案
长弓三石1 天前
鸿蒙网络编程系列59-仓颉版TLS回声服务器示例
harmonyos·鸿蒙·tls·仓颉
袁震2 天前
鸿蒙Harmony-自定义List组件,解决List组件手势滑动点击卡住问题
鸿蒙·list组件·鸿蒙自定义组件封装·鸿蒙滑动卡顿卡住
HarmonyOS小助手3 天前
【宝藏贴】HarmonyOS官方模板优秀案例 · 第1期:便捷生活-购物中心
harmonyos·鸿蒙·鸿蒙生态
HarmonyOS小助手7 天前
“秒开”时代,HarmonyOS预加载让应用启动快如闪电
harmonyos·鸿蒙·鸿蒙生态
_waylau8 天前
跟老卫学HarmonyOS开发:HarmonyOS ArkTS 获取位置服务
华为·开源·harmonyos·鸿蒙
迷曳9 天前
28、鸿蒙Harmony Next开发:不依赖UI组件的全局气泡提示 (openPopup)和不依赖UI组件的全局菜单 (openMenu)、Toast
前端·ui·harmonyos·鸿蒙
脑袋大大的9 天前
跨端分栏布局:从手机到Pad的优雅切换
javascript·uni-app·uniapp·安卓·鸿蒙·app开发·混合开发
屿筱9 天前
鸿蒙与web混合开发双向通信
鸿蒙·harmonyos5