import common from '@ohos.app.ability.common' import fs from '@ohos.file.fs' import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl' import promptAction from '@ohos.promptAction' import { FileTag } from '../config' import { BusinessError } from '@ohos.base' export default class FileUtils { public destFile: string = '' public filePathFdObj: Record = {} private context: common.UIAbilityContext private absolutePath = '/mnt/hmdfs/100/account/device_view/local/files/duolun' constructor(context: common.UIAbilityContext) { this.context = context this.requestPermission() fs.mkdir(this.absolutePath) } async initFolder(folderPath: string): Promise { const folderList = folderPath.split('/').filter(folderName => folderName !== '') let path = this.absolutePath for (const folderName of folderList) { path += `/${folderName}` try { if (!fs.accessSync(path)) { fs.mkdirSync(path) } } catch (e) { this.handleError('初始化文件夹失败', e, folderPath) } } return path } async addFile(filePath: string, content: string): Promise { try { if (fs.accessSync(filePath)) { fs.unlinkSync(filePath) } const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) fs.writeSync(file.fd, content) fs.closeSync(file) console.log(FileTag, '写入文件成功') return true } catch (e) { this.handleError('写入失败', e, filePath) return false } } async editFile(filePath: string, content: string): Promise { try { const file = this.filePathFdObj[filePath] || fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.APPEND | fs.OpenMode.CREATE) fs.writeSync(file.fd, content + '\n') this.filePathFdObj[filePath] = file return file.fd } catch (e) { this.handleError('editFile文件失败', e, filePath) return undefined } } async readFile(filePath: string): Promise { try { return await fs.readText(filePath) } catch (e) { this.handleError('readFile文件失败', e, filePath) return '' } } async closeFile(filePath: string): Promise { const file = this.filePathFdObj[filePath] if (file) { fs.closeSync(file) console.log(FileTag, `${filePath}文件关闭成功`) } } async getDeviceList(folderPath?: string): Promise { return this.getFilePathList(`${this.absolutePath}/${folderPath}`, false) } async getFilePathList(filePath: string, isSdCard: boolean): Promise { try { const filenames = await fs.listFile(filePath) console.log(FileTag, `目录:${filePath}的子文件:${filenames.join(', ')}`) return filenames } catch (e) { this.handleError('获取文件列表失败', e, filePath) return [] } } async deleteF(path: string, type: 1 | 2 | 3): Promise { try { 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}`) } else if (type === 2) { fs.unlinkSync(`${this.absolutePath}/${path}`) } else { fs.unlinkSync(path) } return true } catch (e) { this.handleError('删除文件失败', e, path) return false } } getAbsolutePath(): string { return this.absolutePath } getFileContent(filePath: string): string { const path = `${this.absolutePath}/${filePath}` return fs.readTextSync(path) } private async requestPermission(): Promise { const permissions: Array = [ 'ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA' ] const atManager = abilityAccessCtrl.createAtManager() atManager.requestPermissionsFromUser(this.context, permissions, (code, result) => { if (result.authResults[0] === -1) { promptAction.showToast({ message: '请先授权', duration: 3000, }) } }) } private handleError(message: string, error: BusinessError, filePath: string): void { console.error(FileTag, `${message} ${filePath} ${JSON.stringify(error)}`) promptAction.showToast({ message: `${message} ${filePath} ${JSON.stringify(error)}`, duration: 4000, }) } }