HarmonyOS的fs.openSync不支持創(chuàng)建目錄,所以在進行打開文件的時候,需要先創(chuàng)建目錄才可以:
/*
**寫入文本至文件中
* path: 文件路徑
* contentName: 文件名
* content: 文本內容
*/
writeContent(path:string, content:string | ArrayBuffer, contentName: string){
//存儲前先刪除指定路徑下的文件
this.deleteFile(path, contentName)
//以讀寫和創(chuàng)建的模式打開或創(chuàng)建一個新文件
let savePath = this.cacheDic + '/' + path + '/'
try {
//創(chuàng)建目錄
if (fs.accessSync(savePath, fs.AccessModeType.READ_WRITE) == false) {
fs.mkdirSync(savePath, true)
}
let file = fs.openSync(savePath + contentName, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
//將content寫入到打開的文件中
const result = fs.writeSync(file.fd, content)
//關閉文件
fs.closeSync(file)
} catch (error) {
console.log(error)
}
}
/*
* 刪除指定目錄下的文件
* path: 文件路徑 推薦路徑名由:用戶ID/書本ID/模塊ID/目錄ID+...各級子ID
* */
deleteFile(path:string, contentName: string){
let delPath = this.cacheDic + '/' + path + '/' + contentName
if(fs.accessSync(delPath)){
//如果存在,則使用fs.unlink函數(shù)刪除該文件
try {
fs.unlinkSync(delPath)
} catch (error) {
console.log(error)
}
}
}
/*
* 獲取文本
* path: 文件路徑 推薦路徑名由:用戶ID/書本ID/模塊ID/目錄ID+...各級子ID
* */
getContent(path:string, contentName: string): string | undefined {
let content: string|undefined = undefined
let savePath = this.cacheDic + '/' + path + '/' + contentName
if(fs.accessSync(savePath)){
//如果存在,則讀取文件
try {
content = fs.readTextSync(savePath)
} catch (error) {
console.log(error)
}
}
return content
}