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"
相关推荐
大熊猫侯佩8 小时前
Swift 6.2 列传(第十三篇):香香公主的“倾城之恋”与优先级飞升
swift·编程语言·apple
专业开发者13 小时前
调试 iOS 蓝牙应用的新方法
物联网·macos·ios·cocoa
1024小神15 小时前
Swift配置WKwebview加载网站或静态资源后,开启调试在电脑上debug
swift
米有哥17 小时前
[Embodied AI] Mac上安装ROS2
人工智能·macos·ros2
2501_9275410919 小时前
Adobe Lightroom Classic 2025 Lrc图像处理工具Mac
图像处理·macos·adobe·lightroom·照片美化
2501_9275410919 小时前
AlDente Pro Mac电脑充电限制保护工具
macos·电脑·电脑保护·电脑充电保护
Feibo201119 小时前
永远关闭mac更新
macos
weixin_4624462319 小时前
pkg 手动下载依赖并解决打包时网络下载失败(Win / macOS)
macos·pkg
风为你而吹19 小时前
mac m3上使用vscode + esp-idf开发esp32
ide·vscode·macos
七月shi人19 小时前
使用Node版本管理包n,在MAC电脑权限问题
前端·macos