refactor: 优化file工具函数

This commit is contained in:
wangzhongjie 2025-03-26 13:43:47 +08:00
parent 89db5301ec
commit b7b8ee055e
29 changed files with 394 additions and 414 deletions

View File

@ -1,11 +1,10 @@
import request from '../utils/Request';
import { getSyncData } from '../common/service/initable';
import writeObjectOutNew from './judgeNew';
import FileUtil from '../common/utils/File';
import http from '@ohos.net.http';
import { MASYSSETTableType, RegulatoryInterfaceParams } from '../model';
import { GetSyncData } from '../utils/table/Operation';
import { GetCurrentTime } from '../utils/Common';
import FileUtils from '../utils/FileUtils';
let baseHost: string = AppStorage.get('host');
@ -63,7 +62,7 @@ export async function writeObjectOut(params: RegulatoryInterfaceParams, filePath
`<${key}>${params.drvexam[key]}</${key}>`));
if (filePath) {
const fileUtil = new FileUtil(globalThis.context);
const fileUtil = new FileUtils(globalThis.context);
await fileUtil.initFolder(filePath);
fileUtil.editFile(`${filePath}/wuxi_exam_data.txt`, JSON.stringify({
xtlb: params.xtlb,
@ -106,7 +105,7 @@ export async function writeObjectOut(params: RegulatoryInterfaceParams, filePath
xml: true
},)
if (filePath) {
const fileUtil = new FileUtil(globalThis.context);
const fileUtil = new FileUtils(globalThis.context);
await fileUtil.initFolder(filePath);
fileUtil.editFile(`${filePath}/wuxi_exam_data.txt`, JSON.stringify(temp) + `\n`);
}

View File

@ -1,10 +1,11 @@
import { getSyncData } from '../common/service/initable';
import request from '../utils/Request';
import FileUtil from '../common/utils/File';
import http from '@ohos.net.http';
import common from '@ohos.app.ability.common';
import { DrvexamType, GetJudgeParamsType } from '../model';
import FileUtils from '../utils/FileUtils';
//监管接口序列号映射
const gjxlhObj: Record<string, string> = {
@ -23,7 +24,7 @@ interface WR {
export default async function writeObjectOutNew(data, filePath: string): Promise<WR> {
const context: common.UIAbilityContext = AppStorage.get('context')
const fileUtil = new FileUtil(context);
const fileUtil = new FileUtils(context);
// const { jkid, drvexam } = data;
const basic = await getBasicConfig(data.jkid);
const params = await getParams(data.jkid, data.drvexam);

View File

@ -1,6 +1,5 @@
import promptAction from '@ohos.promptAction'
import router from '@ohos.router'
import FileUtil from '../../common/utils/File'
import { deleteAllFileByPiC, takePhoto } from '../../service/videoService'
import {
delSyncTable,

View File

@ -25,10 +25,11 @@ import USER from '../constants/USER';
import USERLIST from '../constants/USERLIST';
import util from '@ohos.util';
import FileModel from '../../pages/judgeSDK/utils/fileModel';
import FileUtil from '../../common/utils/File';
import { GlobalConfig } from '../../config/index';
import prompt from '@ohos.promptAction';
import DB, { ColumnType } from '../database/DbSql';
import FileUtils from '../../utils/FileUtils';
//读表
//参数平台
@ -348,7 +349,7 @@ export async function upDataZhongxinginitialization(param) {
let flag = true
if (param.singlePlay) {
console.log('teststet0', JSON.stringify(param))
const fileUtil = new FileUtil(param.context)
const fileUtil = new FileUtils(param.context)
const tableList =
['MA_SYSSET', 'MA_SYSTEMPARM', 'MA_MARKRULE', 'MA_MARKRULESET', 'ES_CARINFO', 'MA_MAP_ROAD', 'MA_MAP_ROAD_LANE',
'MAP_SUBITEM', 'MA_T_CARPARMSET', 'MA_MAP_ITEMCLASS', 'MA_MAP_POINT', 'MA_MAP_POINT_ITEM'];

View File

@ -1,271 +0,0 @@
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/duolun'
public destFile:string
public filePathFdObj:Object = {}
constructor(wantInfos) {
const {requestPermission} = this;
this.wantInfos = wantInfos;
requestPermission();
fs.mkdir(this.absolutePath)
}
/*
* @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 thisFile = filePathFdObj[filePath];
try {
if(thisFile){
fs.writeSync(thisFile.fd,newStr)
return fd;
}else{
let file = fs.openSync(filePath, READ_WRITE | APPEND |CREATE);
fs.writeSync(file.fd,newStr)
this.filePathFdObj[filePath] = file
return file.fd
}
} catch (e) {
promptAction.showToast({
message:`editFile文件失败`+ filePath +JSON.stringify(e),
duration:4000,
})
console.error(LOGTAG,JSON.stringify(e))
}
}
/*
* @desc
*
*/
public closeFile = async (filePath:string)=>{
const {filePathFdObj} = this;
const thisFile = filePathFdObj[filePath];
if(thisFile){
fs.closeSync(thisFile);
console.info(LOGTAG,filePath + '文件关闭成功')
}
}
/*
* @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
}
})
}
}

View File

@ -1,5 +1,4 @@
import TcpClient from './TcpClient';
import FileUtil from '../../common/utils/File';
import { GlobalConfig } from '../../config/index';
let intervalSendmsg

View File

@ -1,7 +1,7 @@
//import UdpClient from './UdpClient';
import UdpClientByCenter from './UdpClientByCenter';
import { getChuankouFn } from '../../common/service/indexService';
import FileUtil from '../../common/utils/File';
export async function sendMsg(val) {
// globalThis.udpClient1&&globalThis.udpClient1.sendMsg(val)

View File

@ -2,7 +2,7 @@ import socket from '@ohos.net.socket';
import hilog from '@ohos.hilog';
import { getTCP } from './GlobalTcp';
import prompt from '@ohos.prompt';
import FileUtil from './File';
import App from '@system.app';
const TAG = 'socketTag[TcpDemo.TcpClient]'

View File

@ -1,6 +1,6 @@
import socket from '@ohos.net.socket';
import util from '@ohos.util';
import FileUtil from '../utils/File';
interface RequestKey {
time: string

View File

@ -15,7 +15,6 @@
// @ts-ignore
import socket, { UDPSocket } from '@ohos.net.socket';
import FileUtil from '../../common/utils/File'
const TAG = '[UdpDemo.UdpClient]'
import hilog from '@ohos.hilog';

View File

@ -1,5 +1,4 @@
import util from '@ohos.util';
import FileUtil from './File';
import { uploadExamProgressData, uploadExamProgressData2 } from '../../api/judge';
export default async function uploadProgressData() {

View File

@ -9,4 +9,7 @@ export const UsbTag = '[UsbTag]';
export const VoiceTag = '[VoiceTag]';
//video tag
export const VideoTag = '[VideoTag]';
export const VideoTag = '[VideoTag]';
//file tag
export const FileTag = '[FileTag]';

View File

@ -1,7 +1,6 @@
import common from "@ohos.app.ability.common";
import FileUtil from "../../common/utils/File";
import { GlobalConfig } from "../../config";
import Prompt from "@system.prompt";
import common from '@ohos.app.ability.common';
import { GlobalConfig } from '../../config';
import Prompt from '@system.prompt';
import {
ApiResponseType,
BaseInfoType,
@ -10,19 +9,16 @@ import {
ObtainCarExamInfoRspBody,
TimeSynchronizationParams,
VideoConfig
} from "../../model";
import dayTs from "../../utils/Date";
import { obtainCarExamInfo, timeSynchronization } from "../../api";
} from '../../model';
import dayTs from '../../utils/Date';
import { obtainCarExamInfo, timeSynchronization } from '../../api';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { BusinessError } from "@ohos.base";
import App from "@system.app";
import systemTime from "@ohos.systemTime";
import { VideoConfigData } from "../../mock";
//获取设备信息
export async function GetDeviceInfo(context: common.UIAbilityContext): Promise<string> {
import { BusinessError } from '@ohos.base';
import systemTime from '@ohos.systemTime';
import { VideoConfigData } from '../../mock';
ontext: common.UIAbilityContext): Promise<string> {
return new Promise(async (resolve, reject) => {
const fileUtil = new FileUtil(context)
const fileUtil = new FileUtils(context)
const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/deviceNo.txt');
if (data === '' || data === undefined) {
Prompt.showToast({
@ -112,7 +108,7 @@ export async function TakePhoto(context: common.UIAbilityContext) {
spzd4: false,
}
let map = {}
const fileUtil = new FileUtil(context)
const fileUtil = new FileUtils(context)
const fileData = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/config3.txt');
param = JSON.parse(fileData)
clearInterval(interval)

View File

@ -24,9 +24,7 @@ import {
SYSTEMPARMARR
} from './judgeSDK/api/judgeSDK.d';
import { getSyncData } from '../common/service/initable';
import { judgeConfig } from './judgeSDK/utils/judgeConfig';
import FileUtil from '../common/utils/File';
import SignDisplayCom from './compontents/signDisplayCom';
import {
@ -34,13 +32,13 @@ import {
CommonType,
ES_CARINFOType,
KfdmType,
MASYSSETTableType,
MA_CDSBINFOType,
MA_ITEMINFOType,
MA_MAP_POINTType,
MA_MAP_POINT_ITEMType,
MA_MAP_POINTType,
MA_MARKRULEType,
MA_SYSTEMPARMType,
MASYSSETTableType,
RouteParamsType,
User
} from '../model';
@ -48,6 +46,7 @@ import { GetSyncData } from '../utils/table/Operation';
import dayTs from '../utils/Date';
import { GetCurrentTime } from '../utils/Common';
import { chunkArr } from './judgeSDK/utils/Common';
import FileUtils from '../utils/FileUtils';
@Entry
@Component
@ -626,7 +625,7 @@ struct Index {
async initTrajectoryParam(trajectoryPath: string) {
const { isTrajectoryOpen } = judgeConfig
//轨迹回放读取 systemparam表、markrule表
const fileUtil = new FileUtil(this.context);
const fileUtil = new FileUtils(this.context);
const folderPath = await fileUtil.initFolder(trajectoryPath);
const str = await fileUtil.readFile(folderPath);
const strArr = str.split('\n');

View File

@ -2,10 +2,11 @@ import TopLogo from './compontents/TopLogo'
import { registrationDeviceNo } from '../api/checkCar'
import deviceManager from '@ohos.distributedHardware.deviceManager'
import promptAction from '@ohos.promptAction'
import FileUtil from '../common/utils/File'
import common from '@ohos.app.ability.common'
import { DeviceParamType, ApiResponseType } from '../model'
import { ApiResponseType, DeviceParamType } from '../model'
import dayTs from '../utils/Date'
import FileUtils from '../utils/FileUtils'
@Entry
@Component
@ -121,7 +122,7 @@ struct Index {
deviceName: this.ip,
type: '1'
}
const fileUtil = new FileUtil(this.context)
const fileUtil = new FileUtils(this.context)
const folderPath = await fileUtil.initFolder(`/config`);
fileUtil.addFile(`${folderPath}/deviceNo.txt`, JSON.stringify(param))
AppStorage.setOrCreate('deviceNo', this.ip)

View File

@ -1,11 +1,11 @@
import TopLogo from './compontents/TopLogo';
import ethernet from '@ohos.net.ethernet';
import FileUtil from '../common/utils/File';
import common from '@ohos.app.ability.common';
import { GlobalConfig } from '../config';
import { NetworkConfigType } from '../model/TerminalInfos';
import Prompt from '@system.prompt';
import FileUtils from '../utils/FileUtils';
@Entry
@ -85,7 +85,7 @@ struct Index {
Column() {
Image($r('app.media.terminal_save')).width('20.5%').height('74%').onClick(async () => {
const fileUtil = new FileUtil(this.context)
const fileUtil = new FileUtils(this.context)
const folderPath = await fileUtil.initFolder(`/config`);
const param: NetworkConfigType = {
udplocalIp: this.inputTextList1[9],
@ -149,7 +149,7 @@ struct Index {
}
async aboutToAppear() {
const fileUtil = new FileUtil(this.context)
const fileUtil = new FileUtils(this.context)
const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt');
if (data === '' || data === undefined) {
} else {

View File

@ -18,8 +18,7 @@ import { judgeConfig } from './judgeSDK/utils/judgeConfig';
import { initJudgeUdp } from '../common/utils/UdpJudge';
import errorMsgDialog from './compontents/errorMsgDialog';
import imageBtn from './compontents/imageBtn';
import FileUtil from '../common/utils/File';
import DB from '../common/database/DbSql';
import {
BeginExamRequest,
CarInfoType,
@ -43,6 +42,8 @@ import { GetSyncData } from '../utils/table/Operation';
import { GetCurrentUserKeyValue } from './UserInfo/utils';
import dayTs from '../utils/Date';
import { GetCurrentTime, NumberToByteArray } from '../utils/Common';
import FileUtils from '../utils/FileUtils';
import DB from '../utils/DbSql';
@Entry
@Component
@ -169,7 +170,7 @@ struct UserInfo {
}
}
private fileUtil: FileUtil
private fileUtil: FileUtils
private title = ''
private type = '2'
errorDialog: CustomDialogController = new CustomDialogController({
@ -208,7 +209,7 @@ struct UserInfo {
]
aboutToAppear() {
this.fileUtil = new FileUtil(this.context)
this.fileUtil = new FileUtils(this.context)
this.avPlayer = new VoiceAnnounce();
}

View File

@ -1,11 +1,12 @@
import TopLogo from './compontents/topLogo';
import FileUtil from '../common/utils/File';
import common from '@ohos.app.ability.common';
import promptAction from '@ohos.promptAction';
import { GlobalConfig } from '../config/index';
import { VideoConfigData } from '../mock';
import { CommonType, RecordHandleType, VideoConfig, VideoItemType } from '../model';
import { endRecordVideo, startRecordVideo, takePhoto } from '../utils/Video';
import FileUtils from '../utils/FileUtils';
@Entry
@Component
@ -36,7 +37,7 @@ struct Index {
{ key: '第三路' },
{ key: '第四路' },
]
private fileUtil: FileUtil
private fileUtil: FileUtils
private context = getContext(this) as common.UIAbilityContext;
private controller1: VideoController = new VideoController()
private controller2: VideoController = new VideoController()
@ -592,7 +593,7 @@ struct Index {
// this.ratio = globalThis.ratio
this.ratio = AppStorage.get<number>('ratio')
this.openFlag = true
const fileUtil = new FileUtil(this.context)
const fileUtil = new FileUtils(this.context)
this.fileUtil = fileUtil
this.getVideoConfig()
}

View File

@ -1,6 +1,6 @@
import { voiceService } from '../../service/voiceService';
import { faceCompare } from '../../api/userInfo';
import FileUtil from '../../common/utils/File';
import common from '@ohos.app.ability.common';
import { takePhoto } from '../../service/videoService';
@ -8,6 +8,7 @@ import { GlobalConfig } from '../../config/index';
import { VideoConfigData } from '../../mock';
import { CarInfoType, UDPParamType, VideoConfig } from '../../model';
import { NumberToByteArray } from '../../utils/Common';
import FileUtils from '../../utils/FileUtils';
interface ParamType {
id?: number;
@ -41,7 +42,7 @@ export default struct FaceCompare {
private times = 1; //人脸比对失败次数, 超过3次将不会自动比对需要点击重新打开重新触发
private vocObj: voiceService = null;
private controller: VideoController = new VideoController()
private fileUtil: FileUtil
private fileUtil: FileUtils
private interval: number = -1
private context = getContext(this) as common.UIAbilityContext;
@ -172,7 +173,7 @@ export default struct FaceCompare {
}
async aboutToAppear() {
const fileUtil = new FileUtil(this.context)
const fileUtil = new FileUtils(this.context)
this.carInfo = AppStorage.get('carInfo')
this.fileUtil = fileUtil
this.getVideoConfig()

View File

@ -1,6 +1,6 @@
import { getSyncData } from '../../../common/service/initable';
import { judgeConfig } from '../../judgeSDK/utils/judgeConfig';
import FileUtil from '../../../common/utils/File';
import common from '@ohos.app.ability.common';
import VoiceAnnounce from '../../judgeSDK/utils/voiceAnnouncements';
import { MarkRule, SYSSET } from '../../judgeSDK/api/judgeSDK.d';
@ -9,6 +9,7 @@ import JudgeTask from '../../judgeSDK/utils/judgeTask';
import FilePhoto from '../../judgeSDK/utils/filePhoto';
import { CarInfoType } from '../../../model';
import { GetCurrentTime } from '../../../utils/Common';
import FileUtils from '../../../utils/FileUtils';
interface SEL {
fontColor: string
@ -111,7 +112,7 @@ export default struct DeductedPopup {
// const { isTrajectoryOpen, trajectoryPath } = judgeConfig
const examSubject = this.carInfo.examSubject;
//轨迹回放读取 systemparam表、markrule表
const fileUtil = new FileUtil(this.context);
const fileUtil = new FileUtils(this.context);
const folderPath = await fileUtil.initFolder(judgeConfig.trajectoryPath);
const str = await fileUtil.readFile(folderPath);
const strArr = str.split('\n');

View File

@ -7,7 +7,7 @@ import { EXAMDATA, KSJS, SOUND } from './api/judgeSDK';
import VoiceAnnounce from './utils/voiceAnnouncements';
import FileModel from './utils/fileModel';
import FilePhoto from './utils/filePhoto';
import FileUtil from '../../common/utils/File';
import FileLog from './utils/fileLog';
import JudgeTask from './utils/judgeTask';
import { judgeConfig } from './utils/judgeConfig';
@ -47,6 +47,7 @@ import common from '@ohos.app.ability.common';
import { Array2Byte, convertGpsCoord2, deepClone, fillZero, string2Bytes } from './utils/Common';
import { GetCurrentTime, StringToASCII } from '../../utils/Common';
import UsbService from '../../utils/USB';
import FileUtils from '../../utils/FileUtils';
const judgeTag = 'SURENJUN_JUDGE'
@ -259,7 +260,7 @@ export default class Judge {
private isManual: boolean
//UDP服务序列号
private serialIndex: number
private fileUtil: FileUtil
private fileUtil: FileUtils
private judgeTask: JudgeTask
private tempData: any
//实时计算gps经纬度距离
@ -660,7 +661,7 @@ export default class Judge {
//模型工具
this.fileModel = new FileModel(judgeUI.context);
//文件工具
this.fileUtil = new FileUtil(judgeUI.context)
this.fileUtil = new FileUtils(judgeUI.context)
this.judgeTask = new JudgeTask()
this.usbService = new UsbService();
this.filePhoto = new FilePhoto(judgeUI.context);

View File

@ -1,5 +1,6 @@
import FileUtil from '../../../common/utils/File'
import { GetCurrentTime } from '../../../utils/Common'
import FileUtils from '../../../utils/FileUtils'
interface StuInfo {
name: string
@ -105,7 +106,7 @@ export default class FileLog {
await fileUtil.editFile(`${folderPath}/exam_wuxi_data.txt`, JSON.stringify(lineData), examLineDataFd);
};
//后续文件路径待替换
private fileUtil: FileUtil
private fileUtil: FileUtils
private stuInfo: StuInfo
// 设置文件夹
public initFileLogo = async (stuInfo: StuInfo) => {
@ -121,7 +122,7 @@ export default class FileLog {
}
constructor(context) {
const fileUtil = new FileUtil(context)
const fileUtil = new FileUtils(context)
this.fileUtil = fileUtil
}

View File

@ -1,34 +1,31 @@
import FileUtil from '../../../common/utils/File'
import zlib from '@ohos.zlib';
import promptAction from '@ohos.promptAction';
import router from '@ohos.router';
import FileUtils from '../../../utils/FileUtils';
export default class FileModel{
//后续文件路径待替换
private fileUtil: FileUtil
export default class FileModel {
public folderPath: string
// 设置文件夹
public initFolder = async () => {
const { fileUtil } = this
await fileUtil.initFolder(`/models/model_enc`);
const folderPath = await fileUtil.initFolder(`/models`);
this.folderPath = folderPath;
}
//后续文件路径待替换
private fileUtil: FileUtils
constructor(context){
(async ()=>{
const fileUtil = new FileUtil(context)
constructor(context) {
(async () => {
const fileUtil = new FileUtils(context)
this.fileUtil = fileUtil
})()
}
// 设置文件夹
public initFolder = async () => {
const {fileUtil} = this
await fileUtil.initFolder(`/models/model_enc`);
const folderPath = await fileUtil.initFolder(`/models`);
this.folderPath = folderPath;
}
// 存储zip文件并解压
public storingFiles = async (str) => {
const {fileUtil,folderPath} = this;
await fileUtil.editFile(`${folderPath}/model.zip`,str)
const { fileUtil, folderPath } = this;
await fileUtil.editFile(`${folderPath}/model.zip`, str)
let options = {
level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
@ -41,25 +38,23 @@ export default class FileModel{
`${folderPath}`,
options).then((data) => {
console.log("unzipFile result" + data);
}).catch((err)=>{
}).catch((err) => {
console.log("catch((err)=>" + err);
})
}
//获取文件内容
public getModelContent = (folderPath,fileName) => {
const {fileUtil} = this;
public getModelContent = (folderPath, fileName) => {
const { fileUtil } = this;
try {
const content = fileUtil.getFileContent(`${folderPath}/${fileName}`)
return content;
}catch (e){
console.info('surenjun',JSON.stringify(e))
} catch (e) {
console.info('surenjun', JSON.stringify(e))
promptAction.showToast({
message:`请检查模型路径${folderPath}/${fileName}是否正确!`,
duration:4000
message: `请检查模型路径${folderPath}/${fileName}是否正确!`,
duration: 4000
})
}
}
}

View File

@ -1,7 +1,7 @@
import FileUtil from '../../../common/utils/File'
import { takePhoto } from '../../../service/videoService';
import promptAction from '@ohos.promptAction';
import { judgeConfig } from './judgeConfig'
import { judgeConfig } from './judgeConfig';
import FileUtils from '../../../utils/FileUtils';
interface Params {
userName: string
@ -36,12 +36,12 @@ export default class FilePhoto {
}
}
}
private fileUtil: FileUtil
private fileUtil: FileUtils
constructor(context) {
(async () => {
//TODO 309参数 获取拍照摄像头拍照通道
const fileUtil = new FileUtil(context)
const fileUtil = new FileUtils(context)
const strConfig =
await fileUtil.readFile('/mnt/hmdfs/100/account/device_view/local/files/duolun/config/config3.txt');
const config = JSON.parse(strConfig)

View File

@ -1,38 +1,32 @@
import {
examJudgeMapSetParam,
examJudgeMapSetScaling
} from '../api/index'
import systemTime from '@ohos.systemDateTime';
import FileUtils from '../../../utils/FileUtils';
import { examJudgeMapSetParam, examJudgeMapSetScaling } from '../api/index';
import FileUtil from '../../../common/utils/File'
import FileModel from './fileModel'
import {testRealExam} from '../dataTest/index'
import FileModel from './fileModel';
const judgeTag = 'SURENJUN_JUDGE'
export default class JudgeImg {
private judgeUI
private modelPath:string
private fileModel:FileModel
private fileUtil:FileUtil
private plcData:any
private modelPath: string
private fileModel: FileModel
private fileUtil: FileUtils
private plcData: any
constructor(judgeUI) {
this.modelPath = 'models/model_enc'
this.judgeUI = judgeUI
this.fileUtil = new FileUtil(judgeUI.context)
this.fileUtil = new FileUtils(judgeUI.context)
this.fileModel = new FileModel(judgeUI.context)
this.init()
}
async init(){
async init() {
const isJudgeInitBool = AppStorage.get('isJudgeInitBool');
const {judgeUI} = this;
const { judgeUI } = this;
//TODO 临时处理
setTimeout(async ()=>{
console.info(judgeTag,'1.进入评判入口')
setTimeout(async () => {
console.info(judgeTag, '1.进入评判入口')
await examJudgeMapSetParam(640, 480); //设置参数宽、高
await examJudgeMapSetScaling(100); //设置缩放比例一般默认填100就是100%的意思) 数字越大视野越大数字越小视野越小不能为0
})
@ -42,7 +36,7 @@ export default class JudgeImg {
}
//获取评判初始化数据
getInitInfo = () =>{
getInitInfo = () => {
}
}

View File

@ -4,17 +4,16 @@ import fileAccess from "@ohos.file.fileAccess"
import fs from '@ohos.file.fs'
import abilityAccessCtrl, { Permissions } from "@ohos.abilityAccessCtrl"
import promptAction from "@ohos.promptAction"
import { FileTag } from "../config"
const LOG_TAG = '[file utils]'
export default class FileUtils {
private context: common.UIAbilityContext
private wantInfos: Want[]
private fileAccessHelper: fileAccess.FileAccessHelper
private absolutePath = '/mnt/hmdfs/100/account/device_view/local/files/duolun'
public destFile: string
public filePathFdObj: Record<string, fs.File> = {}
private context: common.UIAbilityContext
private absolutePath = '/mnt/hmdfs/100/account/device_view/local/files/duolun'
constructor(context: common.UIAbilityContext) {
this.context = context
@ -22,25 +21,6 @@ export default class FileUtils {
fs.mkdir(this.absolutePath)
}
private async requestPermission() {
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(this.context, permissions, async (code, result) => {
const permissionRequest = result.authResults[0]
if (permissionRequest == -1) {
promptAction.showToast({
message: "请先授权",
duration: 3000,
})
return
}
})
}
async initFolder(folderPath: string): Promise<string> {
const folderList = folderPath.split('/').filter(folderName => folderName !== '');
let path = this.absolutePath
@ -117,4 +97,83 @@ export default class FileUtils {
return ''
}
}
async closeFile(filePath: string) {
const thisFile = this.filePathFdObj[filePath];
if (thisFile) {
fs.closeSync(thisFile);
console.info(FileTag, filePath + '文件关闭成功')
}
}
async getDeviceList(folderPath?: string) {
return this.getFilePathList(`${this.absolutePath}/${folderPath}`, false)
}
async getFilePathList(filePath: string, isSdCard: boolean): Promise<string[]> {
let fileName: string[] = [];
let sdCardFileName: string[] = [];
try {
const filenames = await fs.listFile(filePath);
for (let i = 0; i < filenames.length; i++) {
console.error(FileTag, `目录:${filePath}的子文件:${filenames[i]}`);
if (isSdCard) {
sdCardFileName.push(filenames[i])
} else {
fileName.push(filenames[i])
}
}
return isSdCard ? sdCardFileName : fileName
} catch (e) {
console.error(FileTag, JSON.stringify(e));
}
}
async deleteF(path: string, type: 1 | 2 | 3) {
if (type === 1) {
const fileList = await this.getFilePathList(`${this.absolutePath}/${path}`, false);
fileList.forEach((fileName) => {
fs.unlinkSync(`${this.absolutePath}/${path}/${fileName}`)
})
fs.rmdirSync(`${this.absolutePath}/${path}`);
return true
} else if (type === 2) {
fs.unlinkSync(`${this.absolutePath}/${path}`);
return true
} else {
fs.unlinkSync(`${path}`);
return true
}
}
getAbsolutePath(): string {
return this.absolutePath
}
getFileContent(filePath: string) {
const path = `${this.absolutePath}/${filePath}`
const str = fs.readTextSync(path);
return str
}
private async requestPermission() {
let permissions: Array<Permissions> = [
'ohos.permission.READ_MEDIA',
'ohos.permission.WRITE_MEDIA'
];
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager()
atManager.requestPermissionsFromUser(this.context, permissions, async (code, result) => {
const permissionRequest = result.authResults[0]
if (permissionRequest == -1) {
promptAction.showToast({
message: "请先授权",
duration: 3000,
})
return
}
})
}
}

View File

@ -0,0 +1,201 @@
import socket from '@ohos.net.socket';
import util from '@ohos.util';
import { BusinessError } from '@ohos.base';
import FileUtils from './FileUtils';
interface RequestKey {
time: string
}
interface RequestCallback {
url: string
type: number
resolve: Function
reject: Function
timeout: number
}
interface RequestParams {
method: string
data: object
type: 0 | 1
contentType: string
timeout?: number
url?: string
serialNumber?: number
isHeartBeat?: string
}
interface Response {
serialNumber: string
data: string
isForwordHttp: string
}
let tag = "tcp request"
class TcpUtils {
private static instance: TcpUtils
private socket: socket.TCPSocket = socket.constructTCPSocketInstance()
private requestMap: Map<string, RequestCallback> = new Map<string, RequestCallback>()
private tick: number
private heartbeat: number
private cache: string = ''
private fileUtil = new FileUtils(AppStorage.get('context'))
private path = ""
constructor() {
if (!TcpUtils.instance) {
TcpUtils.instance = this
}
return TcpUtils.instance
}
async init() {
this.path = await this.fileUtil.initFolder('/config/tcpRequest')
this.socket.on("message", (res) => {
let decoder = util.TextDecoder.create()
let message = decoder.decodeWithStream(new Uint8Array(res.message))
console.log(tag, "on message", message)
this.cache += message
let start = this.cache.indexOf("^#")
let end = this.cache.indexOf("#$")
try {
if (start !== -1 && end !== -1) {
let message = this.cache.slice(start + 2, end)
this.cache = this.cache.slice(end + 2)
let tempIndex = message.indexOf("^#")
while (tempIndex > -1) {
message = message.slice(tempIndex + 2)
tempIndex = message.indexOf("^#")
}
let result: Response = JSON.parse(message)
let key = result.serialNumber
let data = result.data
let isSuccess = result.isForwordHttp === "1"
console.log(tag, "complete message")
let item = this.requestMap.get(key)
console.log(tag, "============", item?.url)
if (this.requestMap.get(key)?.type === 0) {
console.log(tag, "resolve message")
if (isSuccess) {
item?.resolve(JSON.parse(data))
} else {
item?.reject({
code: -1,
message: data || "request failed"
})
}
} else {
console.log(tag, "resolve message")
if (isSuccess) {
item?.resolve(data)
} else {
item?.reject({
code: -1,
message: data || "request failed"
})
}
}
this.requestMap.delete(key)
}
} catch (e) {
console.log(tag, "解析相应失败", JSON.stringify(e))
}
})
this.loop()
return this.socket.connect({
address: { address: "172.37.55.191", port: 19998 }
}).then(() => {
this.heartbeat = setInterval(() => {
this.send("heart", JSON.stringify({
isHeartBeat: 1
}), false)
}, 1000 * 6)
console.log(tag, "connect success")
}).catch((err: BusinessError) => {
console.log(tag, JSON.stringify(err))
})
}
request(url: string, option: RequestParams, resolve, reject) {
let key = new Date().getTime()
this.requestMap.set(key + "", {
url,
resolve,
reject,
timeout: option.timeout,
type: option.type,
})
let message: RequestParams = {
url,
serialNumber: key,
type: option.type,
method: option.method,
data: option.data,
contentType: option.contentType,
isHeartBeat: "0",
}
this.send(key + "", JSON.stringify(message))
}
destroy() {
clearInterval(this.tick)
clearInterval(this.heartbeat)
}
private loop() {
this.tick = setInterval(() => {
let now = new Date().getTime()
this.requestMap.forEach((value, key) => {
if (now - Number(key) >= value.timeout) {
console.log("tcp request timeout url: ", value.url)
console.log("tcp request timeout key: ", key)
value.reject({
message: "tcp request timeout",
code: 2300028
})
this.requestMap.delete(key)
}
})
}, 100)
}
private async send(key: string, message: string, log: boolean = true) {
if (log) {
console.log(tag, 'send', message)
}
this.fileUtil.addFile(this.path + 'temp.txt', `^#${message}#$`)
this.socket.send({
data: `^#${message}#$`
}).then(() => {
if (log) {
console.log(tag, 'send success')
}
}).catch(async (err: BusinessError) => {
if (key !== "heart") {
console.log("tcp request send failed", this.requestMap.get(key).url)
this.requestMap.get(key).reject({
message: "tcp request send failed",
code: 2300007
})
}
await this.socket.close()
this.socket = socket.constructTCPSocketInstance()
await this.socket.connect({
address: { address: "172.37.55.191", port: 19998 }
}).then(res => {
console.log("tcp request reconnect success", JSON.stringify(res))
}).catch((err: BusinessError) => {
console.log("tcp request reconnect failed", JSON.stringify(err))
})
console.log(tag, JSON.stringify(err))
})
}
}
export const tcpUtil = new TcpUtils()

View File

@ -1,16 +1,15 @@
import photoAccessHelper from '@ohos.file.photoAccessHelper'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import record from '@ohos.rtsprecord';
import promptAction from '@ohos.promptAction';
import { GetCurrentTime, IsDaysAgo } from './Common';
import { RecordHandleType, TakePhotoCallbackData, VideoConfig } from '../model';
import common from '@ohos.app.ability.common';
import FileUtil from '../common/utils/File';
import dayTs from './Date';
import { GlobalConfig, VideoTag } from '../config';
import { BusinessError } from '@ohos.base';
import { VideoConfigData } from '../mock';
import { FileHelper } from './FileHelp';
import FileUtils from './FileUtils';
const rtsp_server = record.createServer();
//开始录屏
@ -81,7 +80,7 @@ export async function endRecordVideo(record_handleObj: RecordHandleType) {
export async function saveStartRecordVideo(path: string, context?: common.UIAbilityContext): Promise<RecordHandleType> {
return new Promise(async (resolve, reject) => {
const fileUtil = new FileUtil(context)
const fileUtil = new FileUtils(context)
const fileHelper = new FileHelper();
// const date = dateFormat(new Date).split(' ')[0]
const date = dayTs().format('YYYY-MM-DD HH:mm:ss').split(' ')[0]

View File

@ -1,11 +1,12 @@
import { InitializeTheCentralTableType, ResponseDataType, TableDefinition, User } from '../../model';
import { InitializeTheCentralTableType, ResponseDataType, User } from '../../model';
import DB, { ColumnInfo, ColumnType } from '../DbSql';
import { CenterMap, ParameterPlatform, RemappingTableName } from './Relationship';
import { BusinessError } from '@ohos.base';
import Prompt from '@system.prompt';
import { initialization } from '../../api';
import FileUtil from '../../common/utils/File';
import { GlobalConfig } from '../../config';
import FileUtils from '../FileUtils';
// 建表操作
export async function InitTable() {
@ -86,7 +87,7 @@ export async function DeleteSyncTable(tableName: string): Promise<boolean> {
// 初始化中心表
export async function InitializeTheCentralTable(params: InitializeTheCentralTableType): Promise<boolean> {
return new Promise(async (resolve, reject) => {
const fileUtil = new FileUtil(params.context)
const fileUtil = new FileUtils(params.context)
let flag = false
// 单机模式
if (params.singlePlay) {