macOS 获取文件夹大小

macOS 获取文件夹大小

获取文件夹大小的扩展如下:

swift 复制代码
extension URL {
    var fileSize: Int? { // in bytes
        do {
            let val = try self.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])
            return val.totalFileAllocatedSize ?? val.fileAllocatedSize
        } catch {
            print(error)
            return nil
        }
    }
}
extension FileManager {
    func folderSize(_ dir: URL) -> Int? {
        if let enumerator = self.enumerator(at: dir, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey], options: [], errorHandler: { (_, error) -> Bool in
            print(error)
            return false
        }) {
            var bytes = 0
            for case let url as URL in enumerator {
                bytes += url.fileSize ?? 0
            }
            return bytes
        } else {
            return nil
        }
    }
}

但是返回来的是字节数,如果要转换成 MB 或者 GB,需要自己做转换,那再来扩展吧。

swift 复制代码
extension FileManager {
    func convertBytesToReadableUnit(_ bytes: Int64) -> String {
        let formatter = ByteCountFormatter()
        formatter.countStyle = .binary
        formatter.allowedUnits = [.useAll]
        formatter.includesUnit = true
        formatter.isAdaptive = true
        return formatter.string(fromByteCount: bytes)
    }
}

let bytes: Int64 = 123456789
let readableUnit = FileManager.default.convertBytesToReadableUnit(bytes)
print(readableUnit) // Output: "117.7 MB"
相关推荐
songgeb8 小时前
iOS IAP 本地货币展示:从一个需求到搞清楚 priceLocale
ios·swift
BugShare12 小时前
轻量级原生 macOS 智能剪贴板管理器
macos·贴图
Fleshy数模12 小时前
从课堂视频到结构化教学数据:基于语音识别与 LLM 的智能处理方案
ide·macos·xcode
UXbot13 小时前
AI一次生成iOS和Android双端原型功能详解
android·前端·ios·kotlin·交互·swift
洛水如云16 小时前
系统还原全攻略:Win11/10/7/macOS详细操作指南
windows·macos·电脑
Andya_net16 小时前
MySQL | DBeaver Mac版下载、安装与使用指南
数据库·mysql·macos
2501_9160088918 小时前
Xcode功能、下载、反馈与版本支持详细解析
ide·vscode·macos·ios·个人开发·xcode·敏捷流程
扬帆破浪1 天前
免费开源AI软件.桌面单机版,可移动的AI知识库,察元 AI桌面版:macOS首次启动报无法验证 开发者签名与公证的现实做法
人工智能·macos·开源·知识图谱
irpywp1 天前
合盖断网打断后台计算,Modafinil:一款防休眠菜单栏工具,让 Mac 闭眼继续跑 Agent
macos·ios·开源·github
一只AI打工虾的自我修养2 天前
DeepSeek V4.1 vs Ollama vs LocalClaw:Mac本地AI工具横评
人工智能·windows·macos