HarmonyOS 应用沙箱中的文件判断异常?

在应用中下载了一个压缩文件,并解压到应用沙箱目录/data/storage/el2/base/haps/entry/files/subAppResource,通过Device File Brower可以看到解压后的文件夹,然后使用下面的代码去计算该文件夹下的所有文件大小。

static async getFileSize(path: string) {
  let totalSize: number = 0;
  try {
    const access = await fs.access(path);
    if (access) {
      const stat = await fs.stat(path);
      if (stat.isDirectory()) {
        const files = await fs.listFile(path, { recursion: true });
        for (let file of files) {
          const stat = await fs.stat(file);
          totalSize += stat.size;
        }
      } else {
        totalSize = stat.size;
      }
    }
  } catch (e) {
    console.error(e);
  }
  return totalSize;
}

调用上面方法的代码如下:

const subAppDir = `${this.context.filesDir}/subAppResource`;
const subAppSize: number = await AppFileUtils.getFileSize(subAppDir);

在执行fs.access方法时报错:

13900002 No such file or directory

阅读 646
2 个回答

参考示例如下:

async getFileSize(path: string) {
  let totalSize: number = 0;
  try {
    const access = await fs.access(path);
    if (access) {
      const stat = await fs.stat(path);
      if (stat.isDirectory()) {
        const files = await fs.listFile(path, { recursion: true });
        for (let file of files) {
          const stat = await fs.stat(path + file);
          totalSize += stat.size;
        }
      } else {
        totalSize = stat.size;
      }
    }
  } catch (e) {
    console.error(e);
  }
  return totalSize;
}

解决方案

参考示例:

async getFileSize(path: string) {
  let totalSize: number = 0;
  try {
    const access = await fs.access(path);
    if (access) {
      const stat = await fs.stat(path);
      if (stat.isDirectory()) {
        const files = await fs.listFile(path, { recursion: true });
        for (let file of files) {
          const stat = await fs.stat(path + file);
          totalSize += stat.size;
        }
      } else {
        totalSize = stat.size;
      }
    }
  } catch (e) {
    console.error(e);
  }
  return totalSize;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进