82 lines
3.0 KiB
Plaintext
82 lines
3.0 KiB
Plaintext
import fs from '@ohos.file.fs';
|
|
|
|
//列出资源管理器指定目录下的所有问题件
|
|
export function HilogSadboxFontDirFile(ctx: Context,dirName:string){
|
|
// 获取资源管理器
|
|
const rm = ctx?.filesDir+'/'+dirName+'/';
|
|
fs.listFile(rm).then((filenames: Array<string>) => {
|
|
console.info('沙箱文件信息'); // 打印成功日志
|
|
console.info('目录路径:'+rm); // 打印成功日志
|
|
console.log('指定目录文件数: ' + filenames.length) // 打印文件数量
|
|
// 遍历打印所有文件名到控制台
|
|
for (let i = 0; i < filenames.length; i++) {
|
|
console.log('文件名:', filenames[i]);
|
|
}
|
|
}).catch((err: BusinessError) => {
|
|
// 捕获并打印文件列表获取失败的错误信息
|
|
console.error('list file failed with error message: ' + err.message + ', error code: ' + err.code);
|
|
});
|
|
}
|
|
export function CheckExistDir(dir:string):boolean{
|
|
if (!dir || typeof dir !== 'string') {
|
|
console.error('Invalid directory path provided.');
|
|
return false;
|
|
}
|
|
try {
|
|
// 使用 fs.stat 获取路径的状态信息
|
|
fs.accessSync(dir);
|
|
const stat = fs.statSync(dir);
|
|
if (stat.isDirectory()) {
|
|
console.info(`Directory exists: ${dir}`);
|
|
return true;
|
|
} else {
|
|
console.info(`Path exists but is not a directory: ${dir}`);
|
|
return false;
|
|
}
|
|
} catch (error) {
|
|
// fs.stat 如果路径不存在会抛出错误
|
|
const businessError = error as BusinessError;
|
|
if (businessError.code === 101) { // 错误码 101 通常代表文件或目录不存在,请根据实际文档确认
|
|
console.info(`Directory does not exist: ${dir}`);
|
|
} else {
|
|
// 其他错误,如权限不足等
|
|
console.error(`Error checking directory existence: ${businessError.message}, code: ${businessError.code}`);
|
|
}
|
|
return false; // 发生错误,视为目录不存在或无法访问
|
|
}
|
|
}
|
|
//复制字体到沙盒指定目录
|
|
//SandBoxFontDir:"/data/storage/el2/base/haps/entry/files/fonts"
|
|
export function ExtractDir(ctx: Context,dirName:string):boolean{
|
|
//err->true表示复制成功
|
|
//err->表示复制失败
|
|
try {
|
|
//初始化源Fonts目录和沙箱Fonts目录路径
|
|
let srcPath = ctx?.resourceDir+ '/'+dirName+'/';
|
|
let destPath = ctx?.filesDir + '/'+dirName+'/';
|
|
//检测目录是否存在
|
|
let srcDirState:boolean=CheckExistDir(srcPath);
|
|
let destDirState:boolean=CheckExistDir(destPath);
|
|
//源字体目录不存在则返回.->直接无法系统
|
|
if(!srcDirState){
|
|
return false;
|
|
}
|
|
//如果沙箱目录不存在则创建目录
|
|
if(!destDirState){
|
|
fs.mkdir(destPath);
|
|
console.info('Created sandbox directory successfully:', destPath);
|
|
}
|
|
fs.copyDir(srcPath, destPath);
|
|
console.info('Fonts copied to sandbox successfully.');
|
|
return true;
|
|
} catch (err) {
|
|
let msg = 'Unknown error';
|
|
if (err instanceof Error) {
|
|
msg = err.message;
|
|
} else if (typeof err === 'string') {
|
|
msg = err;
|
|
}
|
|
console.error(`Copy failed: ${msg}`);
|
|
return false;
|
|
}
|
|
} |