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"
相关推荐
1024小神16 小时前
Mac 副屏快速左 50% 分屏
macos
00后程序员张19 小时前
iOS 打包方式汇总 从 Xcode Archive 到轻量级工具链的 IPA 构建
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
菜鸟歪歪歪1 天前
idea中增加api中转站教程(Mac,Window通用)
macos·intellij-idea
sweet丶1 天前
Swift 黑魔法:`@dynamicMemberLookup`
swift·rxswift
大熊猫侯佩1 天前
SwiftUI 侦探笔记:iPhone 14 失踪的“刘海”与侯佩的像素诡计
swiftui·swift·apple
大熊猫侯佩1 天前
WWDC26 新 @ContentBuilder 修饰符:SwiftUI 终于有了户口本
swiftui·swift·wwdc
小石潭记丶2 天前
本地mac创建秘钥,然后远程登录Linux服务器
linux·服务器·macos
小呀小叮当~2 天前
OpenAI Codex 桌面版(Windows / macOS)体验分享:AI 编程效率再次提升
人工智能·windows·macos
myenjoy_12 天前
I2S 音频与数字音频接口详解
macos·音视频·xcode
东坡肘子2 天前
当 Linux 成为“空气”:容器、Agent 与不再重要的“桌面之争” -- 肘子的 Swift 周报 #143
人工智能·swiftui·swift