import { ReadFileSuccessResult, ReadFileFailResult, ReadFile,ReadFileOptions } from "../interface.uts" import { WriteFileSuccessResult, WriteFileFailResult, WriteFile,WriteFileOptions } from "../interface.uts" import File from "java.io.File" import UTSAndroid from 'io.dcloud.uts.UTSAndroid'; import Base64 from "android.util.Base64" import Environment from 'android.os.Environment'; export { ReadFileOptions, WriteFileOptions } from "../interface.uts" /** * 获取文件内容 */ export const readFile : ReadFile = function (options : ReadFileOptions) { // 判断type 是否合法 if(options.type != 'base64' && options.type != 'text'){ let ret : ReadFileFailResult = { errCode: -1, errMsg: "type error.", errSubject: "uni-getFileContent" } options.fail?.(ret) options.complete?.(ret) return } /** * 执行真正的加载行为,为了避免阻塞分发到 io任务序列 */ UTSAndroid.dispatchAsync('io',function(_){ let filePath = UTSAndroid.convert2AbsFullPath(options.path) let targetFile = new File(filePath) if (!targetFile.exists()) { let ret : ReadFileFailResult = { errCode: -2, errMsg: "file not found.", errSubject: "uni-getFileContent" } options.fail?.(ret) options.complete?.(ret) return } if (targetFile.isDirectory()) { let ret : ReadFileFailResult = { errCode: -3, errMsg: "error:file is a Directory.", errSubject: "uni-getFileContent" } options.fail?.(ret) options.complete?.(ret) return } /** * 文件超过16M,会超过应用内存 */ if (targetFile.length() > 16 * 1024 * 1024) { let ret : ReadFileFailResult = { errCode: -3, errMsg: "error:file is bigger than 16M", errSubject: "uni-getFileContent" } options.fail?.(ret) options.complete?.(ret) return } if(options.type == 'base64'){ // base64 let byteArray = targetFile.readBytes() let base64Content = Base64.encodeToString(byteArray,Base64.NO_WRAP) let ret : ReadFileSuccessResult = { content: base64Content, } options.success?.(ret) options.complete?.(ret) }else{ // text let text = targetFile.readText() let ret : ReadFileSuccessResult = { content: text } options.success?.(ret) options.complete?.(ret) } },null) } /** * 获取文件内容 */ export const writeFile : WriteFile = function (options : WriteFileOptions) { // 判断type 是否合法 let nextFile = new File(UTSAndroid.getAppContext()?.getFilesDir(),options.path) console.log(nextFile.getPath()) if(nextFile.exists() && nextFile.isDirectory()){ // 出错了,目标文件已存在,并且是个目录 let ret : WriteFileFailResult = { errCode: -2, errMsg: "file exist and is a directory.", errSubject: "uni-writeFile" } options.fail?.(ret) options.complete?.(ret) return } UTSAndroid.dispatchAsync('io',function(_){ /** * 如果上一级目录不存在,创建之 */ if(!nextFile.parentFile.exists()){ nextFile.parentFile.mkdirs() } if(!nextFile.exists()){ nextFile.createNewFile() } // 写入文本,暂时只支持覆盖写入 nextFile.writeText(options.content) let ret : WriteFileSuccessResult = { filePath: nextFile.getPath() } options.success?.(ret) options.complete?.(ret) },null) }