harmony-utils之FileUtil,文件相關工具類
harmony-utils 簡介與說明
harmony-utils 一款功能豐富且極易上手的HarmonyOS工具庫,借助眾多實用工具類,致力于助力開發者迅速構建鴻蒙應用。其封裝的工具涵蓋了APP、設備、屏幕、授權、通知、線程間通信、彈框、吐司、生物認證、用戶首選項、拍照、相冊、掃碼、文件、日志、異常捕獲、字符、字符串、數字、集合、日期、隨機、base64、加密、解密、JSON等一系列的功能和作,能夠滿足各種不同的開發需求。
picker_utils 是harmony-utils拆分出來的一個子庫,包含 PickerUtil、PhotoHelper、ScanUtil。
下載安裝ohpm i @pura/harmony-utils
ohpm i @pura/picker_utils
//全局初始化方法,在UIAbility的onCreate方法中初始化 AppUtil.init()
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
AppUtil.init(this.context);
}
API方法與使用
getFilesDirPath 獲取文件目錄下的文件夾路徑或文件路徑
let path1 = FileUtil.getFilesDirPath('');
let path2 = FileUtil.getFilesDirPath("", "TEST.txt");
let path3 = FileUtil.getFilesDirPath('download/wps/ppt', 'dev.text');
let path4 = FileUtil.getFilesDirPath("download/wps/wps");
let path5 = FileUtil.getFilesDirPath(`${getContext().filesDir}/download/apk`, "app.apk");
let path6 = FileUtil.getFilesDirPath(`${getContext().filesDir}/download/wps/ppt`);
getCacheDirPath 獲取緩存目錄下的文件夾路徑或文件路徑
let path7 = FileUtil.getCacheDirPath('download/wps/ppt', 'dev_xs.text');
getTempDirPath 獲取臨時目錄下的文件夾路徑或文件路徑
let path8 = FileUtil.getTempDirPath('download/wps/ppt', 'dev_max.text');
hasDirPath 判斷是否是完整路徑
let hasDirPath1 = FileUtil.hasDirPath("download/wps/測試.PDF");
let hasDirPath2 = FileUtil.hasDirPath(`${FileUtil.getFilesDirPath("download/wps", "測試文檔.doc")}`);
getFileUri 通過URI或路徑,獲取FileUri
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
let fileUri = FileUtil.getFileUri(filePath);
getFileName 通過URI或路徑,獲取文件名
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
let name = FileUtil.getFileName(filePath);
getFilePath 通過URI或路徑,獲取文件路徑
let uri = "file://com.tong.yuyan.utils/data/storage/el2/base/haps/entry/files/download/wps/txt/demo.txt";
let filePath = FileUtil.getFilePath(strUri);
getParentUri 通過URI或路徑,獲取對應文件父目錄的URI
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
if (FileUtil.accessSync(filePath)) {
let parentUri = FileUtil.getParentUri(filePath);
} else {
ToastUtil.showToast("文件不存在,請先創建和寫入");
}
getParentPath 通過URI或路徑,獲取對應文件父目錄的路徑名
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
if (FileUtil.accessSync(filePath)) {
let parentPath = FileUtil.getParentPath(filePath);
} else {
ToastUtil.showToast("文件不存在,請先創建和寫入");
}
getUriFromPath 以同步方法獲取文件URI
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
let uri = FileUtil.getUriFromPath(filePath);
getFileExtention 根據文件名獲取文件后綴
let fileExtention = FileUtil.getFileExtention("/data/storage/el2/base/haps/entry/files/download/demo.txt");
let fileExtention2 = FileUtil.getFileExtention("妹紙.png");
getFileDirSize 獲取指定文件夾下所有文件的大小或指定文件大小
let path = FileUtil.getFilesDirPath("");
let fileDirSize = FileUtil.getFileDirSize(path);
ToastUtil.showToast(`文件夾下所有文件的大小:${fileDirSize}`);
isFile 判斷文件是否是普通文件
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
if (FileUtil.accessSync(filePath)) {
let isFile = FileUtil.isFile(filePath);
} else {
ToastUtil.showToast("文件不存在,請先創建和寫入");
}
isDirectory 判斷文件是否是目錄
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
if (FileUtil.accessSync(filePath)) {
let isDirectory = FileUtil.isDirectory(filePath);
} else {
ToastUtil.showToast("文件不存在,請先創建和寫入");
}
rename 重命名文件或文件夾
let path = FileUtil.getFilesDirPath("", "test_cpoy.txt");
let path2 = FileUtil.getFilesDirPath("", "test_cpoy2.txt");
if (FileUtil.accessSync(path)) {
FileUtil.rename(path, path2);
ToastUtil.showToast("重命名成功");
} else {
ToastUtil.showToast("文件不存在,請先創建或拷貝 目標文件")
}
mkdir 創建目錄,當recursion指定為true,可多層級創建目錄
let filePath = FileUtil.getFilesDirPath('app/download/test/wps/txt');
FileUtil.mkdirSync(filePath);
rmdir 刪除整個目錄
let dirPath = FileUtil.getFilesDirPath("");
FileUtil.rmdir(dirPath).then(() = > {
ToastUtil.showToast("刪除整個目錄成功");
});
unlink 刪除單個文件
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
FileUtil.unlink(filePath).then(() = > {
ToastUtil.showToast("刪除單個文件成功");
}).catch((err: BusinessError) = > {
ToastUtil.showToast("刪除單個文件失敗!");
});
access 檢查文件是否存在
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
let bl = FileUtil.accessSync(filePath);
open 打開文件,支持使用URI打開文件
let path = FileUtil.getFilesDirPath("", "test.txt");
let file = FileUtil.openSync(path);
read 從文件讀取數據
let path = FileUtil.getFilesDirPath("", "test.txt");
let file = FileUtil.openSync(path);
FileUtil.writeSync(file.fd, `"HUAWEI MatePad 11.5"S 對應的API版本是多少?`)
FileUtil.closeSync(file.fd); //關閉文件
file = FileUtil.openSync(path);
let buffer: ArrayBuffer = new ArrayBuffer(180);
FileUtil.readSync(file.fd, buffer);
let bufferStr = StrUtil.bufferToStr(buffer);
FileUtil.closeSync(file.fd); //關閉文件
readText 基于文本方式讀取文件(即直接讀取文件的文本內容)
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
if (FileUtil.accessSync(filePath)) {
let txt = FileUtil.readTextSync(filePath);
LogUtil.info(txt);
} else {
ToastUtil.showToast("文件不存在,請先創建和寫入")
}
write 將數據寫入文件
let path = FileUtil.getFilesDirPath("", "test.txt");
let file = FileUtil.openSync(path);
FileUtil.writeSync(file.fd, `"HUAWEI MatePad 11.5"S 對應的API版本是多少?`)
FileUtil.closeSync(file.fd); //關閉文件
writeEasy 將數據寫入文件,并關閉文件
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
FileUtil.writeEasy(filePath, "harmony-utils 一款高效的OpenHarmony/HarmonyOS工具包。幫助開發者快速構建鴻蒙應用。");
close 關閉文件
let path = FileUtil.getFilesDirPath("", "test.txt");
let file = FileUtil.openSync(path);
FileUtil.closeSync(file.fd); //關閉文件
stat 獲取文件詳細屬性信息
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
if (FileUtil.accessSync(filePath)) {
let stat = FileUtil.statSyncfilePath);
let jsonStr = `${stat.ino} - ${stat.mode} - ${stat.uid} - ${stat.gid} - ${stat.size} - ${stat.atime} - ${stat.mtime} - ${stat.isDirectory()} - ${stat.isFile()}`;
LogUtil.info(jsonStr);
} else {
ToastUtil.showToast("文件不存在,請先創建和寫入 目標文件")
}
listFile 列出文件夾下所有文件名,支持遞歸列出所有文件名(包含子目錄下),支持文件過濾
let dirPath = FileUtil.getFilesDirPath("");
let listFile = FileUtil.listFileSync(dirPath, { recursion: true });
let listFileStr = listFile.join('n');
copyFile 復制文件
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt')
let path = FileUtil.getFilesDirPath("download/wps", "test_cpoy.txt");
if (FileUtil.accessSync(filePath)) {
FileUtil.copyFile(filePath, path).then(() = > {
let size = FileUtil.lstatSync(path).size;
ToastUtil.showToast("文件拷貝成功:" + size);
})
} else {
ToastUtil.showToast("文件不存在,請先創建和寫入 目標文件");
}
copy 拷貝文件或者目錄,支持拷貝進度監聽
let path = FileUtil.getFilesDirPath("download");
let path2 = FileUtil.getFilesDirPath("copy目錄");
if (FileUtil.accessSync(path)) {
let progressListener: fs.ProgressListener = (progress: fs.Progress) = > {
LogUtil.info(`progressSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`);
};
FileUtil.copy(FileUtil.getUriFromPath(path), FileUtil.getUriFromPath(path2),
{ "progressListener": progressListener }).then(() = > {
let size = FileUtil.lstatSync(path2).size;
ToastUtil.showToast("文件夾拷貝成功:" + size);
}).catch((err: BusinessError) = > {
ToastUtil.showToast("文件夾拷貝異常:" + err.message);
})
} else {
ToastUtil.showToast("文件夾不存在,請先創建");
}
copyDir 復制源文件夾至目標路徑下,只能復制沙箱里的文件夾
let path = FileUtil.getFilesDirPath("download");
let path2 = FileUtil.getFilesDirPath("copyDir目錄");
if (FileUtil.accessSync(path)) {
FileUtil.copyDir(path, path2).then(() = > {
let size = FileUtil.lstatSync(path2).size;
ToastUtil.showToast("文件夾拷貝成功:" + size);
}).catch((err: BusinessError) = > {
ToastUtil.showToast("文件夾拷貝異常:" + err.message);
})
} else {
ToastUtil.showToast("文件夾不存在,請先創建");
}
moveFile 移動文件
let path = FileUtil.getFilesDirPath("download/wps", "test_cpoy.txt");
let path2 = FileUtil.getFilesDirPath("download/txt", "test_cpoy.txt");
if (FileUtil.accessSync(path)) {
FileUtil.moveFile(path, path2).then(() = > {
ToastUtil.showToast("移動文件成功");
})
} else {
ToastUtil.showToast("文件不存在")
}
moveDir 移動源文件夾至目標路徑下
let path = FileUtil.getFilesDirPath("copyDir目錄");
let path2 = FileUtil.getFilesDirPath("moveDir目錄");
if (FileUtil.accessSync(path)) {
FileUtil.moveDir(path, path2).then(() = > {
ToastUtil.showToast("文件夾移動成功");
}).catch((err: BusinessError) = > {
ToastUtil.showToast("文件夾移動異常:" + err.message);
})
} else {
ToastUtil.showToast("文件夾不存在,請先創建");
}
truncate 截斷文件
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
FileUtil.truncate(filePath, 15);
lstat 獲取鏈接文件信息
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
let stat = FileUtil.lstatSync(filePath);
let jsonStr = `${stat.ino} - ${stat.mode} - ${stat.uid} - ${stat.gid} - ${stat.size} - ${stat.atime} - ${stat.mtime} - ${stat.isDirectory()} - ${stat.isFile()}`;
LogUtil.info(jsonStr);
fsync 同步文件數據
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
let file = fs.openSync(filePath);
FileUtil.fsync(file.fd).then(() = > {
LogUtil.info("同步成功!");
}).catch((err: BusinessError) = > {
LogUtil.error("同步失敗, error信息: " + err.message + ", error code: " + err.code);
}).finally(() = > {
FileUtil.closeSync(file);
});
fdatasync 實現文件內容數據同步
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
let file = FileUtil.openSync(filePath);
FileUtil.fdatasync(file.fd).then(() = > {
LogUtil.info("sync data succeed");
}).catch((err: BusinessError) = > {
LogUtil.error("sync data failed with error message: " + err.message + ", error code: " + err.code);
}).finally(() = > {
FileUtil.closeSync(file);
});
createStream 基于文件路徑打開文件流
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
FileUtil.createStream(filePath, "a+").then((stream: fs.Stream) = > {
stream.closeSync();
LogUtil.info("createStream succeed");
}).catch((err: BusinessError) = > {
LogUtil.error("createStream failed with error message: " + err.message + ", error code: " + err.code);
});
fdopenStream 基于文件描述符打開文件流
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
let file = FileUtil.openSync(filePath);
FileUtil.fdopenStream(file.fd, "r+").then((stream: fs.Stream) = > {
console.info("openStream succeed");
stream.closeSync();
}).catch((err: BusinessError) = > {
console.error("openStream failed with error message: " + err.message + ", error code: " + err.code);
fs.closeSync(file); //文件流打開失敗后,文件描述符需要手動關閉
});
mkdtemp 創建臨時目錄
let path = FileUtil.getFilesDirPath() + "/臨時目錄/download/temp";
let tempPath = FileUtil.mkdtempSync(path);
ToastUtil.showToast("操作成功: " + tempPath);
dup 將文件描述符轉化為File
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo.txt');
let file = FileUtil.openSync(filePath, fs.OpenMode.READ_WRITE);
let fd: number = file.fd;
let file2 = FileUtil.dup(fd);
LogUtil.info("The name of the file2 is " + file2.name);
FileUtil.closeSync(file);
FileUtil.closeSync(file2);
utimes 修改文件最近訪問時間屬性
let filePath = FileUtil.getFilesDirPath('download/wps/txt', 'demo_time.txt');
let file = FileUtil.openSync(filePath, fs.OpenMode.READ_WRITE);
FileUtil.writeSync(file.fd, "harmony-utils一款高效的OpenHarmony/HarmonyOS工具包。幫助開發者快速構建鴻蒙應用!");
FileUtil.closeSync(file);
FileUtil.utimes(filePath, new Date().getTime());
getFormatFileSize 格式化文件大小
let sizeStr = FileUtil.getFormatFileSize(1020450901);
ToastUtil.showToast(`文件大小:${sizeStr}`);
checkPersistentPermission 校驗所選擇的多個文件或目錄URI持久化授權。(需要權限:ohos.permission.FILE_ACCESS_PERSIST)
//cacheUri 見使用案例源碼
if (StrUtil.isNotEmpty(this.cacheUri)) {
let policie: fileShare.PolicyInfo = {
uri: this.cacheUri,
operationMode: fileShare.OperationMode.READ_MODE | fileShare.OperationMode.WRITE_MODE
}
FileUtil.checkPersistentPermission([policie]).then(() = > {
this.jsonStr = `檢查權限,成功!n${this.cacheUri}`;
}).catch((err: BusinessError) = > {
this.jsonStr = `檢查權限,異常:n${JSON.stringify(err)}`;
});
} else {
ToastUtil.showToast("請先調用saveDocument()保存文件,在操作!");
}
persistPermission 對所選擇的多個文件或目錄URI持久化授權。(需要權限:ohos.permission.FILE_ACCESS_PERSIST)
//cacheUri 見使用案例源碼
if (StrUtil.isNotEmpty(this.cacheUri)) {
FileUtil.persistPermissionEasy([this.cacheUri]).then(() = > {
this.jsonStr = `授權,已授權!n${this.cacheUri}`;
let file = FileUtil.openSync(this.cacheUri); //uri是否可用,讀取文件
this.jsonStr = this.jsonStr + `nn文件名:${file.name}`;
LogUtil.error("file: " + file.name);
}).catch((err: BusinessError) = > {
this.jsonStr = `授權,異常:n${JSON.stringify(err)}`;
});
} else {
ToastUtil.showToast("請先調用saveDocument()保存文件,在操作!");
}
revokePermission 對所選擇的多個文件或目錄uri取消持久化授權。(需要權限:ohos.permission.FILE_ACCESS_PERSIST)
//cacheUri 見使用案例源碼
if (StrUtil.isNotEmpty(this.cacheUri)) {
FileUtil.revokePermissionEasy([this.cacheUri]).then(() = > {
this.jsonStr = `移除授權,成功!`;
let file = FileUtil.openSync(this.cacheUri); //uri是否可用,讀取文件
this.jsonStr = this.jsonStr + `nn文件名:${file.name}`;
LogUtil.error("file: " + file.name);
}).catch((err: BusinessError) = > {
this.jsonStr = `移除授權,異常:n${JSON.stringify(err)}`;
});
} else {
ToastUtil.showToast("請先調用saveDocument()保存文件,在操作!");
}
activatePermission 對已經持久化授權的權限進行使能操作,否則已經持久化授權的權限仍存在不能使用的情況。(需要權限:ohos.permission.FILE_ACCESS_PERSIST)
//cacheUri 見使用案例源碼
if (StrUtil.isNotEmpty(this.cacheUri)) {
FileUtil.activatePermissionEasy([this.cacheUri]).then(() = > {
this.jsonStr = `使能操作,成功!n${this.cacheUri}`;
}).catch((err: BusinessError) = > {
this.jsonStr = `使能操作,異常:n${JSON.stringify(err)}`;
})
} else {
ToastUtil.showToast("請先調用saveDocument()保存文件,在操作!");
}
deactivatePermission 取消使能授權過的多個文件或目錄。(需要權限:ohos.permission.FILE_ACCESS_PERSIST)
//cacheUri 見使用案例源碼
if (StrUtil.isNotEmpty(this.cacheUri)) {
FileUtil.deactivatePermissionEasy([this.cacheUri]).then(() = > {
this.jsonStr = `取消使能授權,成功!n${this.cacheUri}`;
}).catch((err: BusinessError) = > {
this.jsonStr = `取消使能授權,異常:n${JSON.stringify(err)}`;
})
} else {
ToastUtil.showToast("請先調用saveDocument()保存文件,在操作!");
}
創作不易,請給童長老點贊
聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。
舉報投訴
-
Harmony
+關注
關注
0文章
104瀏覽量
2984
發布評論請先 登錄
相關推薦
熱點推薦
harmony-utils之LocationUtil,定位相關工具類
harmony-utils之LocationUtil,定位相關工具類 harmony-utils
harmony-utils之PreviewUtil,文件預覽工具類
harmony-utils之PreviewUtil,文件預覽工具類 harmony-utils
harmony-utils之SnapshotUtil,截圖相關工具類
harmony-utils之SnapshotUtil,截圖相關工具類 harmony-utils
harmony-utils之WindowUtil,窗口相關工具類
harmony-utils之WindowUtil,窗口相關工具類 harmony-utils 簡
harmony-utils之AuthUtil,生物認證相關工具類
# harmony-utils之AuthUtil,生物認證相關工具類 ## harmony-utils
harmony-utils之NetworkUtil,網絡相關工具類
harmony-utils之NetworkUtil,網絡相關工具類 harmony-utils
評論