复制文件到应用沙箱缓存目录

import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import hilog from '@ohos.hilog';

const TAG = 'FileUtil';

export class FileUtil {
  /**
   * 复制文件到应用沙箱缓存目录
   * @param sourceFilePath 源文件路径
   * @param context UIAbility上下文
   * @returns 目标文件路径或null(失败时)
   */
  static async copyToCacheDir(sourceFilePath: string, context: common.UIAbilityContext): Promise<string | null> {
    let sourceFile = null;
    let targetFile = null;
    
    try {
      // 打开源文件
      sourceFile = fs.openSync(sourceFilePath, fs.OpenMode.READ_ONLY);
      hilog.info(0x0000, TAG, `开始复制文件: ${sourceFile.name}`);
      
      // 构建目标文件路径
      const targetFilePath = `${context.cacheDir}/${sourceFile.name}`;
      
      // 打开目标文件(不存在则创建)
      targetFile = fs.openSync(targetFilePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      
      // 执行复制操作
      fs.copyFileSync(sourceFile.fd, targetFile.fd);
      hilog.info(0x0000, TAG, `文件复制成功: ${targetFilePath}`);
      
      return targetFilePath;
    } catch (err) {
      hilog.error(0x0000, TAG, `文件复制失败: ${JSON.stringify(err)}`);
      return null;
    } finally {
      // 确保文件描述符被关闭
      if (sourceFile) {
        fs.closeSync(sourceFile);
      }
      if (targetFile) {
        fs.closeSync(targetFile);
      }
    }
  }
  
  /**
   * 复制文件到应用沙箱指定目录
   * @param sourceFilePath 源文件路径
   * @param context UIAbility上下文
   * @param targetDir 目标目录(如cacheDir、filesDir等)
   * @returns 目标文件路径或null(失败时)
   */
  static async copyToSandboxDir(
    sourceFilePath: string, 
    context: common.UIAbilityContext,
    targetDir: string
  ): Promise<string | null> {
    let sourceFile = null;
    let targetFile = null;
    
    try {
      sourceFile = fs.openSync(sourceFilePath, fs.OpenMode.READ_ONLY);
      const targetFilePath = `${targetDir}/${sourceFile.name}`;
      
      targetFile = fs.openSync(targetFilePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      fs.copyFileSync(sourceFile.fd, targetFile.fd);
      
      hilog.info(0x0000, TAG, `文件复制到沙箱目录成功: ${targetFilePath}`);
      return targetFilePath;
    } catch (err) {
      hilog.error(0x0000, TAG, `文件复制到沙箱目录失败: ${JSON.stringify(err)}`);
      return null;
    } finally {
      if (sourceFile) fs.closeSync(sourceFile);
      if (targetFile) fs.closeSync(targetFile);
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值