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"
相关推荐
iOS门童16 小时前
macOS 应用"已损坏"无法打开?一文搞懂 Gatekeeper 与解决方案
macos
NPE~18 小时前
[工具分享]Maccy —— 优雅的 macOS 剪贴板历史管理工具
macos·教程·工具·实用工具
差不多程序员19 小时前
Mac安装OpenClaw-cn保姆级教程
macos
dzl8439419 小时前
mac 安装python
开发语言·python·macos
升讯威在线客服系统20 小时前
从 GC 抖动到稳定低延迟:在升讯威客服系统中实践 Span 与 Memory 的高性能优化
java·javascript·python·算法·性能优化·php·swift
Bruce_Liuxiaowei20 小时前
在 macOS 上通过 Docker 本地安装 OpenClaw 完整教程
macos·docker·容器·openclaw
阿捏利21 小时前
详解Mach-O(十五)Mach-O __DATA_CONST
macos·ios·c/c++·mach-o
ShikiSuen21 小时前
macOS 的 CpLk 中英切换卡顿的元凶在 InputMethodKit 本身
macos
Swift社区21 小时前
LeetCode 390 消除游戏 - Swift 题解
leetcode·游戏·swift
xiayutian_c21 小时前
如虎添翼-MacOS
macos