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"
相关推荐
桌角的眼镜1 天前
模拟开发授权平台
macos·ios·xcode
[奋斗不止]1 天前
MacOS 安装 cocoapods
macos·cocoapods·mac cocoapods·macos cocoapods
程序务虚论2 天前
抓取工具Charles配置教程(mac电脑+ios手机)
macos·ios·https·charles
WMSmile2 天前
macOS 安装了Docker Desktop版终端docker 命令没办法使用
macos·docker·容器
爱幻想-hjyp2 天前
Mac M1安装 Docker Desktop 后启动没反应
macos·docker·eureka
一只帆記2 天前
M1 Mac pip3 install错误记录
python·macos·pip
安和昂3 天前
iOS 类与对象底层原理
macos·ios·cocoa
开开心心就好3 天前
无限制文本转语音解决方案
开发语言·人工智能·macos·微信·pdf·c#·语音识别
ElenaYu3 天前
罗技K580蓝牙键盘连接mac pro
macos·计算机外设
吉凶以情迁3 天前
c# window桥接mac电脑直接开发ios直接win开发运行 弹出模拟器
macos·ios