data-migration/entry/src/main/ets/backupExtension/backupTransferManagers/FileTransferManager.ets
2024-05-28 09:45:01 +08:00

61 lines
2.0 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { BaseTransferManager } from './BaseTransferManager';
export class FileTransferManager extends BaseTransferManager {
/**
* 双框架文件移动到单框架指定目录
*
* @param context context上下文
*/
transfer(context: common.Context): void {
// move源文件到目标路径
if (this.moveFiles(context)) {
// 文件move成功的处理
return;
}
// 文件move失败的处理
}
private moveFiles(context: common.Context): boolean {
// 文件移动逻辑
try {
// ce路径前缀数据迁移时会将双框架/data/data/${双包名}下的数据迁移至此处
let cePathPrefix: string = `/data/storage/el2/backup/restore/${this.BundleName}/ce`
// 需要移动的源文件路径根据实际路径来指定如这里移动files/sourceFiles下面的所有文件
let sourceFilePath: string = cePathPrefix + '/files/sourceFiles'
if (!fs.accessSync(sourceFilePath)) {
return false
}
// 得到源路径下面所有的文件和目录
let listFileNames: string[] = fs.listFileSync(sourceFilePath)
if (!listFileNames || listFileNames.length === 0) {
return false
}
// 目标路径根据实际情况来指定, 如这里是沙箱路径files下面的targetFiles目录
let targetPath: string = context.filesDir + '/targetFiles'
// 目标目录不存在,则需要创建
if (!fs.accessSync(targetPath)) {
fs.mkdirSync(targetPath);
}
// 遍历源路径下面的文件或目录,进行移动
listFileNames.forEach((fileName: string) => {
let srcPath: string = `${sourceFilePath}/${fileName}`
let destPath: string = `${targetPath}/${fileName}`
if (fs.statSync(srcPath).isFile()) {
fs.moveFileSync(srcPath, destPath)
} else {
fs.moveDirSync(srcPath, targetPath)
}
})
return true
} catch (error) {
// 异常自行处理
return false
}
}
}