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"
相关推荐
蜜汁小强2 小时前
macOS 上卸载并重新安装HomeBrew
macos
新手村领路人2 小时前
macOS 原生自带的缩放功能设置
macos
小胖燕4 小时前
macOS 系统本地部署 CVAT 进行数据标注
macos·cvat
海棠AI实验室4 小时前
第 3 篇:服务编排与自启动——把 Mac 变成“稳定可运维”的家庭 AI 机房
运维·人工智能·macos
蜜汁小强5 小时前
macOS 上管理不同版本的python
开发语言·python·macos
Edward.W6 小时前
iOS 17+真机命令行操作对照表
macos·ios·cocoa
1telescope1 天前
MacBook 安装 nvm 管理 Node.js 多版本教程
macos·node.js
1telescope1 天前
MacBook 安装 Oh My Zsh 完整教程
macos·mac
蜜汁小强1 天前
macOS 上的git代理配置在哪里
git·macos·代理模式·proxy模式
蜜汁小强1 天前
macOS 上升级到 python 3.12
开发语言·python·macos