如何在 OS X 上用 Swift 获取目录大小

11

我正在尝试使用Swift在OS X上获取目录及其内容的大小。到目前为止,我只能获取目录本身的大小,没有它的内容。对于我的大多数目录,它通常显示6,148字节的值,但实际上会有所不同。

我已经尝试了来自下面文件中的directorySize()函数,但它也返回了6,148字节。

https://github.com/amosavian/ExtDownloader/blob/2f7dba2ec1edd07282725ff47080e5e7af7dabea/Utility.swift

而我也不能让这里的Swift答案适用于我的目的。

如何根据路径获取文件大小?

我正在使用Xcode 7.0并运行OS X 10.10.5。

6个回答

25

更新: Xcode 11.4.1 • Swift 5.2


extension URL {
    /// check if the URL is a directory and if it is reachable 
    func isDirectoryAndReachable() throws -> Bool {
        guard try resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true else {
            return false
        }
        return try checkResourceIsReachable()
    }

    /// returns total allocated size of a the directory including its subFolders or not
    func directoryTotalAllocatedSize(includingSubfolders: Bool = false) throws -> Int? {
        guard try isDirectoryAndReachable() else { return nil }
        if includingSubfolders {
            guard
                let urls = FileManager.default.enumerator(at: self, includingPropertiesForKeys: nil)?.allObjects as? [URL] else { return nil }
            return try urls.lazy.reduce(0) {
                    (try $1.resourceValues(forKeys: [.totalFileAllocatedSizeKey]).totalFileAllocatedSize ?? 0) + $0
            }
        }
        return try FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil).lazy.reduce(0) {
                 (try $1.resourceValues(forKeys: [.totalFileAllocatedSizeKey])
                    .totalFileAllocatedSize ?? 0) + $0
        }
    }

    /// returns the directory total size on disk
    func sizeOnDisk() throws -> String? {
        guard let size = try directoryTotalAllocatedSize(includingSubfolders: true) else { return nil }
        URL.byteCountFormatter.countStyle = .file
        guard let byteCount = URL.byteCountFormatter.string(for: size) else { return nil}
        return byteCount + " on disk"
    }
    private static let byteCountFormatter = ByteCountFormatter()
}

使用方法:

do {
    let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    if let sizeOnDisk = try documentDirectory.sizeOnDisk() {
        print("Size:", sizeOnDisk) // Size: 3.15 GB on disk
    }
} catch {
    print(error)
}

下面有2个屏幕截图。我无法使它们的大小匹配。 我的文档目录大约是1.50 GB https://drive.google.com/file/d/0B8F7IPsTUK7gUEVzeU5JRTF0Qms/view?usp=sharing但控制台仅报告了272字节 https://drive.google.com/file/d/0B8F7IPsTUK7gaDBiZkdfREZhWkE/view?usp=sharing - theCalmChameleon
这是一个本地文件夹吗? - Leo Dabus
这就是我对你的代码做出的唯一更改,只是为了确保它是正确的,我加入了一个打印文档URL的语句。 - theCalmChameleon
这可能是因为您的所有文件都位于子文件夹中。我在这里进行了测试,显示大约大小为6,358。 - Leo Dabus
枚举选项。由于此方法仅执行浅层枚举,因此不允许防止进入子目录或包的选项;唯一支持的选项是NSDirectoryEnumerationSkipsHiddenFiles。 - Leo Dabus
显示剩余7条评论

6

对于正在寻找Swift 5+和Xcode 11+解决方案的所有人,请查看这个gist

func directorySize(url: URL) -> Int64 {
    let contents: [URL]
    do {
        contents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey])
    } catch {
        return 0
    }

    var size: Int64 = 0

    for url in contents {
        let isDirectoryResourceValue: URLResourceValues
        do {
            isDirectoryResourceValue = try url.resourceValues(forKeys: [.isDirectoryKey])
        } catch {
            continue
        }
    
        if isDirectoryResourceValue.isDirectory == true {
            size += directorySize(url: url)
        } else {
            let fileSizeResourceValue: URLResourceValues
            do {
                fileSizeResourceValue = try url.resourceValues(forKeys: [.fileSizeKey])
            } catch {
                continue
            }
        
            size += Int64(fileSizeResourceValue.fileSize ?? 0)
        }
    }
    return size
}

4

以下是 Swift 3 版本:

 func findSize(path: String) throws -> UInt64 {

    let fullPath = (path as NSString).expandingTildeInPath
    let fileAttributes: NSDictionary = try FileManager.default.attributesOfItem(atPath: fullPath) as NSDictionary

    if fileAttributes.fileType() == "NSFileTypeRegular" {
        return fileAttributes.fileSize()
    }

    let url = NSURL(fileURLWithPath: fullPath)
    guard let directoryEnumerator = FileManager.default.enumerator(at: url as URL, includingPropertiesForKeys: [URLResourceKey.fileSizeKey], options: [.skipsHiddenFiles], errorHandler: nil) else { throw FileErrors.BadEnumeration }

    var total: UInt64 = 0

    for (index, object) in directoryEnumerator.enumerated() {
        guard let fileURL = object as? NSURL else { throw FileErrors.BadResource }
        var fileSizeResource: AnyObject?
        try fileURL.getResourceValue(&fileSizeResource, forKey: URLResourceKey.fileSizeKey)
        guard let fileSize = fileSizeResource as? NSNumber else { continue }
        total += fileSize.uint64Value
        if index % 1000 == 0 {
            print(".", terminator: "")
        }
    }

    if total < 1048576 {
        total = 1
    }
    else
    {
        total = UInt64(total / 1048576)
    }

    return total
}

enum FileErrors : ErrorType {
    case BadEnumeration
    case BadResource
}

输出值以MB为单位。

源代码转换自:https://gist.github.com/rayfix/66b0a822648c87326645


1
请注意,您还需要(从引用的源代码):枚举 FileErrors: Error { case BadEnumeration case BadResource } - Ron Diel
我也添加了ErrorType枚举。谢谢Dan。 - B.Tekkan

2

对于任何想要实现最基本功能的人(在macOS和iOS上都适用):

Swift 5最基本版本

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 directorySize(_ dir: URL) -> Int? { // in bytes
        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
        }
    }
}

使用方法

let fm = FileManager.default
let tmp = fm.temporaryDirectory

if let size = fm.directorySize(tmp) {
    print(size)
}

这个简化版的代码没有预先检查目录是否为目录或文件是否为文件(无论哪种情况都会返回nil),而且结果以原生格式返回(字节作为整数)。

0

Swift 3 版本

private func sizeToPrettyString(size: UInt64) -> String {

    let byteCountFormatter = ByteCountFormatter()
    byteCountFormatter.allowedUnits = .useMB
    byteCountFormatter.countStyle = .file
    let folderSizeToDisplay = byteCountFormatter.string(fromByteCount: Int64(size))

    return folderSizeToDisplay

}

-1

基于https://dev59.com/NFwY5IYBdhLWcg3wRF9S#32814710的答案,我使用现代Swift并发创建了一个类似的版本。

编辑:在此处添加代码的主要部分。 完整版本(复制/粘贴到Playground中)在此gist中:https://gist.github.com/a01d1c5b0c58f37dd14ac9ec2e1f6092

enum FolderSizeCalculatorError: Error {
    case urlUnreachableOrNotDirectory
    case failToEnumerateDirectoryContent
    case failToGenerateString
}

class FolderSizeCalculator {
    private let fileManager: FileManager

    private static let byteCountFormatter: ByteCountFormatter = {
        let formatter = ByteCountFormatter()
        formatter.countStyle = .file
        return formatter
    }()
    
    init(fileManager: FileManager = .default) {
        self.fileManager = fileManager
    }
    
    /// Returns formatted string for total size on disk for a given directory URL
    /// - Parameters:
    ///   - url: top directory URL
    ///   - includingSubfolders: if true, all subfolders will be included
    /// - Returns: total byte count, formatted (i.e. "8.7 MB")
    func formattedSizeOnDisk(atURLDirectory url: URL,
                             includingSubfolders: Bool = true) async throws -> String {
        let size = try await sizeOnDisk(atURLDirectory: url, includingSubfolders: includingSubfolders)
        
        guard let byteCount = FolderSizeCalculator.byteCountFormatter.string(for: size) else {
            throw FolderSizeCalculatorError.failToGenerateString
        }
        
        return byteCount
    }
    
    
    /// Returns total size on disk for a given directory URL
    /// Note: `totalFileAllocatedSize()` is available for single files.
    /// - Parameters:
    ///   - url: top directory URL
    ///   - includingSubfolders: if true, all subfolders will be included
    /// - Returns: total byte count
    func sizeOnDisk(atURLDirectory url: URL,
                    includingSubfolders: Bool = true) async throws -> Int {
        guard try url.isDirectoryAndReachable() else {
            throw FolderSizeCalculatorError.urlUnreachableOrNotDirectory
        }
        
        return try await withCheckedThrowingContinuation { continuation in
            var fileURLs = [URL]()
            do {
                if includingSubfolders {
                    // Enumerate directories and sub-directories
                    guard let urls = fileManager.enumerator(at: url, includingPropertiesForKeys: nil)?.allObjects as? [URL] else {
                        throw FolderSizeCalculatorError.failToEnumerateDirectoryContent
                    }
                    fileURLs = urls
                } else {
                    // Only contents of given directory
                    fileURLs = try fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: nil)
                }
                
                let totalBytes = try fileURLs.reduce(0) { total, url in
                    try url.totalFileAllocatedSize() + total
                }
                continuation.resume(with: .success(totalBytes))
            } catch {
                continuation.resume(with: .failure(error))
            }
        }
    }
}

extension URL {
    /// check if the URL is a directory and if it is reachable
    func isDirectoryAndReachable() throws -> Bool {
        guard try resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true else {
            return false
        }
        return try checkResourceIsReachable()
    }
    
    func totalFileAllocatedSize() throws -> Int {
        try resourceValues(forKeys: [.totalFileAllocatedSizeKey]).totalFileAllocatedSize ?? 0
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接