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"
相关推荐
2501_916007477 小时前
不越狱如何查看iOS 应用的详细信息及其文件目录结构
android·macos·ios·小程序·uni-app·cocoa·iphone
芒鸽9 小时前
macos上Rust 命令行工具鸿蒙化适配完全攻略
macos·rust·harmonyos
山有木兮啊9 小时前
VSCode Remote-SSH 连接Mac卡在初始化VSCode
vscode·macos·ssh
一个写bug的程序员10 小时前
Mac自启服务关闭方式
macos
梁下轻语的秋缘10 小时前
初学者避坑指南:Mac 虚拟机搭建 Keil5 STM32 环境 + 解决 ST-Link USB Command Error 报错
windows·stm32·macos
天荒地老笑话么10 小时前
macOS 终端:本机隐藏用户名,但 SSH 登录时仍显示(Oh My Zsh + agnoster,更安全)
windows·macos·网络安全
Digitally10 小时前
Mac 屏幕录制工具:12 款 Mac 屏幕录制工具
macos
阿赛工作室1 天前
mac系统使用Hbuilderx调试安装app
macos
weixin_462446231 天前
Linux/Mac 一键自动配置 JAVA_HOME 环境变量(含 JDK 完整性校验)
java·linux·macos
Frank学习路上1 天前
【Qt】问题记录ld: framework ‘AGL‘ not found on MacOS 26
开发语言·qt·macos