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"
相关推荐
June bug12 小时前
【领域知识】广告全链路测试
macos·objective-c·cocoa
fendoudexiaoniao_ios13 小时前
iOS 列表拖拽cell排序
ios·swift
作孽就得先起床14 小时前
Xcode设置中文
macos
smileSunshineMan15 小时前
本地mac-openclaw安装
macos·openclaw
fish_study_csdn16 小时前
自己的mac 电脑上部署本地大模型
macos
绝世唐门三哥17 小时前
Mac 查看手机信息工具 + platform-tools 使用全指南
windows·macos
qinyia19 小时前
如何彻底卸载macOS上的conda并清理环境变量配置
macos·conda
0wioiw01 天前
Onesignal(Xcode)
ide·macos·xcode
哈基米~南北绿豆1 天前
虚拟机体验:在Windows/Mac上运行鸿蒙PC开发环境
windows·macos·harmonyos
大熊猫侯佩2 天前
Swift 6 驱魔实录:揭开 Combine 与 @Sendable 的“血色契约”
swift·block·combine·preconcurrency·sendable·mainactor·isolation