surenjun 4bfbfe1516 Revert "feat:评判优化"
This reverts commit 8d489592
2024-12-30 16:40:54 +08:00

258 lines
7.4 KiB
TypeScript
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 Want from '@ohos.app.ability.Want'
import promptAction from '@ohos.promptAction'
import fileAccess from '@ohos.file.fileAccess'
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'
import common from '@ohos.app.ability.common'
import fs from '@ohos.file.fs'
const LOGTAG = 'LOGTAG'
export default class FileUtil{
private context: common.UIAbilityContext
private wantInfos: Want[]
private fileAccessHelper: fileAccess.FileAccessHelper
//后续文件路径待替换
private absolutePath = '/mnt/hmdfs/100/account/device_view/local/files'
public destFile:string
public filePathFdObj:Object = {}
constructor(wantInfos) {
const {requestPermission} = this;
this.wantInfos = wantInfos;
requestPermission();
}
/*
* @desc 校验文件夹,文件夹不存在会创建,支持嵌套
*
*/
public initFolder = async (folderPath:string) => {
const {absolutePath} = this;
const folderList = folderPath.split('/').filter(folderName => folderName !== '');
let path = absolutePath
folderList.forEach((folderName=>{
path += `/${folderName}`;
try {
const isExit = fs.accessSync(path);
if(!isExit){
fs.mkdirSync(path)
}
} catch (e) {
console.info('初始化文件夹失败',path)
promptAction.showToast({
message:`初始化文件夹失败`+ folderPath + JSON.stringify(e),
duration:4000,
})
}
}));
return path;
}
/*
* @desc 创建并覆盖文件
*
*/
public addFile = async (filePath:string,content:string,type?:string)=>{
const { READ_WRITE,CREATE,APPEND }= fs.OpenMode
const isExit = fs.accessSync(filePath);
//文件存在先删除
if(isExit){
fs.unlinkSync(filePath);
}
try {
let file = fs.openSync(filePath, READ_WRITE | CREATE);
//追加写入文件
fs.writeSync(file.fd,content)
fs.closeSync(file)
console.error(LOGTAG,'写入文件成功')
return true
}catch (e){
promptAction.showToast({
message:`addFile文件失败`+ filePath +JSON.stringify(e),
duration:4000,
})
console.error(LOGTAG,'写入失败',JSON.stringify(e))
}
}
/*
* @desc 创建或者编辑文件
*
*/
public editFile = async (filePath:string,content:string,fd?:number)=>{
const {filePathFdObj} = this;
const { READ_WRITE,CREATE,APPEND }= fs.OpenMode
const newStr = content + '\n'
const thisFileFd = filePathFdObj[filePath];
try {
if(thisFileFd){
fs.writeSync(fd,newStr)
return fd;
}else{
let file = fs.openSync(filePath, READ_WRITE | APPEND |CREATE);
fs.writeSync(file.fd,newStr)
this.filePathFdObj[filePath] = file.fd
return file.fd
}
} catch (e) {
promptAction.showToast({
message:`editFile文件失败`+ filePath +JSON.stringify(e),
duration:4000,
})
console.error(LOGTAG,JSON.stringify(e))
}
}
/*
* @desc 读取文件
*
**/
public readFile = async (filePath:string) => {
try{
console.log('strrr',filePath)
const str = await fs.readText(filePath);
return str
}catch (e){
promptAction.showToast({
message:`读取文件失败`+ filePath +JSON.stringify(e),
duration:4000,
})
console.log('readFile文件失败'+ filePath +JSON.stringify(e))
return ''
}
}
/*
* @desc获取系统目录里的文件列表
*/
public getDeviceList = async (folderPath?:string)=>{
const {absolutePath,getFilePathList} = this;
return getFilePathList(`${absolutePath}/${folderPath}`,false)
};
// 删除文件夹或者文件
/*
* @desc 删除文件夹或者文件
* @param{{type}} 1:文件夹 2文件 3自定义目录下文件
**/
public deleteF = async (path:string,type: 1 | 2 | 3) => {
const {getFilePathList,absolutePath} = this
if(type === 1){
const fileList = await getFilePathList(`${absolutePath}/${path}`,false);
fileList.forEach(filePath =>{
fs.unlinkSync(`${absolutePath}/${path}/${filePath}`);
})
fs.rmdirSync(`${absolutePath}/${path}`);
return true
}
if(type === 2){
fs.unlinkSync(`${absolutePath}/${path}`);
return true
}
if(type === 3){
fs.unlinkSync(`${path}`);
return true
}
}
// 获取系统文件绝对路径
public getAbsolutePath = () =>{
const {absolutePath} = this;
return absolutePath
}
// 检索文件列表
public getSdCardPathList = async () => {
this.wantInfos = await fileAccess.getFileAccessAbilityInfo();
const {wantInfos,context} = this;
const fileAccessHelper = fileAccess.createFileAccessHelper(this.context,this.wantInfos);
this.fileAccessHelper = fileAccessHelper;
let isDone = false;
let rootIterator = null;
try {
rootIterator = await fileAccessHelper.getRoots();
while (!isDone) {
let isDones = false;
let rootInfo = rootIterator.next();
isDone = rootInfo.done; //返回true结束
console.error(LOGTAG, "根目录迭代器对象 next result = " + JSON.stringify(rootInfo));
if (!isDone) {
let deviceType = rootInfo.value.deviceType;
let displayName = rootInfo.value.displayName;
let uri:string = rootInfo.value.uri;
let deviceFlags = rootInfo.value.deviceFlags;
console.error(LOGTAG,`设备类型:${deviceType},设备名称:${displayName}设备根目录Uri${uri},设备支持的能力:${deviceFlags}`);
if(uri.indexOf('/mnt/external/')>0){
// if('vol-8-1' ==displayName){
this.destFile = uri.split('ExternalFileManager')[1]+'/'
console.error(LOGTAG,`外置存储路径:`+this.destFile);
this.getFilePathList(this.destFile,true)
}
}
}
} catch (error) {
console.error(LOGTAG,"getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
}
}
public getFileContent = (filePath:string) => {
const {absolutePath} = this;
const { READ_WRITE }= fs.OpenMode
const path = `${absolutePath}/${filePath}`
const str = fs.readTextSync(path);
return str
}
private getFilePathList = async (filePath:string,isSdcard:boolean) => {
let fileName = [],sdCardFileName = [];
try {
const filenames = await fs.listFile(filePath);
for (let i = 0; i < filenames.length; i++) {
console.error(LOGTAG,`目录:${filePath}的子文件:${filenames[i]}`);
if(isSdcard){
sdCardFileName.push(filenames[i])
}else{
fileName.push(filenames[i])
}
}
return isSdcard ? sdCardFileName : fileName
}catch (e){
console.error(LOGTAG,JSON.stringify(e));
}
}
// 文件系统初始化
private requestPermission = async () => {
const {context,absolutePath} = this;
let permissions: Array<Permissions> = [
'ohos.permission.READ_MEDIA',
'ohos.permission.WRITE_MEDIA'
];
this.wantInfos = await fileAccess.getFileAccessAbilityInfo();
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager()
atManager.requestPermissionsFromUser(context, permissions , async (code, result) => {
const permissionRequest = result.authResults[0]
if(permissionRequest == -1){
promptAction.showToast({
message: "请先授权",
duration:3000,
})
return
}
})
}
}