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"
相关推荐
春波petal11 小时前
Mac nvm 永久固定 Node 版本(新开终端自动生效)
macos·nvm
小宋102114 小时前
Mina Meeting Assistant 新手极速上手指南
ide·macos·ai·xcode·mina
AI创界者14 小时前
ComfyUI v8 极致整合包发布!Win/Mac 双平台完美适配 + 多卡并行加速,开启 AI 绘画新时代
人工智能·macos
最后一支迷迭香14 小时前
Mac使用docker下的两个冷知识
macos·docker·容器
2501_9151063215 小时前
iOS开发工具有哪些?iOS 开发每个阶段的实用工具
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
你疯了抱抱我15 小时前
【Mac】安装并配置HomeBrew;ARM GCC;make;OpenOCD
arm开发·macos
春波petal16 小时前
Mac把底部Dock固定在笔记本主屏(自带屏幕),4步搞定
macos
键盘飞行员16 小时前
macOS Trae 解决 Codex 插件不显示问题(官方适配版)
macos·编辑器·ai编程
一个人旅程~17 小时前
win11中启用经典win10右键菜单和还原默认win11右键菜单如何操作
windows·经验分享·macos·电脑
花伤情犹在1 天前
Mac上 10 分钟快速安装Hermes
macos·ai·agent·hermes