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

【鸿蒙在 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;}}
}
http://www.xdnf.cn/news/12174.html

相关文章:

  • 解决 Git 访问 GitHub 时的 SSL 错误
  • nginx怎么使用nginx-rtmp-module模块实现直播间功能
  • Apache DolphinScheduler 和 Apache Airflow 对比
  • EXCEL通过DAX Studio获取端口号连接PowerBI
  • 深入解析光敏传感技术:嵌入式仿真平台如何重塑电子工程教学
  • 探秘半导体制造设备钢结构防震基座的承重奥秘-江苏泊苏系统集成有限公司
  • Linux-07 ubuntu 的 chrome 启动不了
  • 船舶事故海上搜救VR情景演练全场景 “复刻”,沉浸式救援体验​
  • .net Span类型和Memory类型
  • 使用vite-plugin-html在 HTML 文件中动态注入数据,如元数据、环境变量、标题
  • LeetCode-70. 爬楼梯
  • 第二章支线八 ·CSS终式:Tailwind与原子风暴
  • uniapp中使用aixos 报错
  • Kafka入门-消费者
  • vue2中使用jspdf插件实现页面自定义块pdf下载
  • vue2 , el-select 多选树结构,可重名
  • 网页抓取混淆与嵌套数据处理流程
  • C:\Users\中文名修改为英文名
  • 大模型微调技术全景图:从全量更新到参数高效适配
  • 用 NGINX 构建高效 POP3 代理`ngx_mail_pop3_module`
  • 厂区能源监控系统:网关赋能下的高效能源管理与环保监测
  • Elasticsearch:spring2.x集成elasticsearch8.x
  • OpenCV在图像上绘制文字示例
  • Apache Druid 架构深度解析:构建高性能分布式数据存储系统
  • LINUX编译vlc
  • Qt多线程访问同一个数据库源码分享(基于Sqlite实现)
  • [论文阅读] 人工智能+软件工程 | MemFL:给大模型装上“项目记忆”,让软件故障定位又快又准
  • 阿里云服务器安装nginx并配置前端资源路径(前后端部署到一台服务器并成功访问)
  • 聊一聊 .NET在Linux下的IO多路复用select和epoll
  • Neo4j图数据库管理:原理、技术与最佳实践