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);
}
}
}
复制文件到应用沙箱缓存目录
最新推荐文章于 2026-03-03 00:25:38 发布

567

被折叠的 条评论
为什么被折叠?



