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"
相关推荐
不羁的木木4 小时前
MacOS 安装 OpenClaw 并接入飞书机器人(保姆级教程 + 常见问题解决)
macos·机器人·飞书
AuLuo-4 小时前
openclaw(小龙虾)本地安装部署MAC版本homebrew)
macos
denggun123455 小时前
Sendable 协议-Swift 结构化并发的核心安全保障
ios·swift
DvLee10245 小时前
让旧Mac再战几年:使用 OpenCore Legacy Patcher 升级不支持的 macOS(完整教程)
macos·macbook·opencore
一只小白菜5 小时前
在 macOS 上配置 OpenClaw 连接本地 Ollama 完整指南
macos
一乐小哥6 小时前
Zsh 与 Bash 配置文件:用法、区别、迁移
macos·shell
黄昏贩卖机7 小时前
mac M芯片安装pytorch
人工智能·pytorch·macos
EZ_Python7 小时前
如何在 Windows 上将 Python 脚本打包为 macOS 原生应用
windows·python·macos
NGBQ121387 小时前
Keep It 2.7.10 全解析:Mac 端专业笔记管理工具深度指南
笔记·macos
米 柴8 小时前
Mac电脑配置环境变量
macos