HarmonyOS 如何通过文件描述符fd获取路径

HarmonyOS
2024-12-27 15:55:32
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

可以通过fs.dup接口将文件描述符转化为File,然后通过file.path获取路径。

参考代码如下:

import fs from '@ohos.file.fs';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct FdTest {
  build() {
    Column(){
      Text('FdTest')
        .onClick(() =>{
          let context: common.Context = getContext(this)
          let pathDir = context.filesDir;
          let filePath = pathDir + "/test.txt";
          let file1 = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
          try {
            let res = fs.accessSync(filePath);
            if (res) {
              console.info("file exists");
            } else {
              console.info("file not exists");
            }
          } catch(error) {
            let err: BusinessError = error as BusinessError;
            console.error("accessSync failed with error message: " + err.message + ", error code: " + err.code);
          }
          let fd: number = file1.fd;
          let file2 = fs.dup(fd);
          console.info("The name of the file2 is " + file2.name);
          console.info("The Path of the file2 is " + file2.path)
          fs.closeSync(file1);
          fs.closeSync(file2);
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

参考文档:fs.dup

分享
微博
QQ
微信
回复
2024-12-27 18:13:11
相关问题
HarmonyOS avplayer播放fd路径文件报错
577浏览 • 1回复 待解决
HarmonyOS文件路径 fd 和 internal 的区别
1439浏览 • 1回复 待解决
文件上传的本地路径如何获取
791浏览 • 1回复 待解决
如何获取文件绝对路径
2524浏览 • 1回复 待解决
如何获取应用自身的源文件路径
2320浏览 • 1回复 待解决
如何获取profile路径下资源文件
2063浏览 • 1回复 待解决
如何获取资源文件的全路径
2179浏览 • 1回复 待解决
鸿蒙如何获取资源文件种的路径
16947浏览 • 3回复 待解决