鴻蒙常見的文件操作

一、學習筆記

HarmonyOS NEXT API 12


二、代碼實例

class FileUtils {

  /**
   * 從文件路徑獲取文件名
   * @param filePath 文件路徑
   * @returns
   */
  getFileName(filePath:string):string{
    const parts = filePath.split('/');
    const fileName = parts[parts.length - 1];
    return fileName
  }

  /**
   * 創(chuàng)建目錄
   * @param path 目錄路徑
   */
  creatFolder(path: string){
    if(!fs.accessSync(path)){
      fs.mkdirSync(path)  // 同步創(chuàng)建
    }
  }

  /**
   * 刪除文件夾、文件
   * @param path 路徑
   */
  deleteFile(path: string){

    if(!fs.accessSync(path)){
      // 文件不存在
      return
    }
    if(fs.statSync(path).isDirectory()){
      fs.rmdirSync(path)  // 同步刪除
    }else {
      fs.unlinkSync(path)  // 同步刪除
    }
  }


  /**
   * 目錄名規(guī)范校驗
   * @param name
   * @returns
   */
  isValidDirectoryName(name: string): boolean {
    // 規(guī)則:
    // 1. 名稱長度必須在 1 到 255 個字符之間。
    // 2. 只能包含字母、數(shù)字、空格、下劃線、連字符和點。
    // 3. 不能以點開頭或結(jié)尾,也不能包含連續(xù)的點。
    // 4. 不能包含操作系統(tǒng)保留的關鍵詞(這里省略具體實現(xiàn),因為需要特定于操作系統(tǒng))
    const minLength = 1;
    const maxLength = 255;
    const validChars = /^[a-zA-Z0-9\s_\-.]+$/; // 正則表達式,匹配允許的字符
    const startsOrEndsWithDot = /^\.|\.$/; // 正則表達式,匹配以點開頭或結(jié)尾
    const containsConsecutiveDots = /\.{2,}/; // 正則表達式,匹配連續(xù)的點
    // 檢查長度
    if (name.length < minLength || name.length > maxLength) {
      return false;
    }
    // 檢查字符
    if (!validChars.test(name)) {
      return false;
    }
    // 檢查以點開頭或結(jié)尾
    if (startsOrEndsWithDot.test(name)) {
      return false;
    }
    // 檢查連續(xù)的點
    if (containsConsecutiveDots.test(name)) {
      return false;
    }
    // 可選:檢查保留字(這里省略,因為實現(xiàn)會依賴于操作系統(tǒng))
    // 如果所有檢查都通過,則返回 true
    return true;
  }

  // 文件壓縮
  zipCompress(srcPath: string, desName: string) {
    let inFile = srcPath  // 源文件路徑
    let outFile = desName   // 壓縮到指定路徑
    let options: zlib.Options = {
      level: zlib.CompressLevel.COMPRESS_LEVEL_BEST_COMPRESSION,
      memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
      strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY
    }
    if (!fs.accessSync(inFile)) {
      // 文件不存在
      return
    }
      zlib.compressFile(inFile, outFile, options).then((data: void) => {
        AppLogger.debug('壓縮成功')
      }).catch((errData: BusinessError) => {
        AppLogger.error(`壓縮出錯 errCode:${errData.code}  message:${errData.message}`)
      })

  }

}
export default new FileUtils();
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容