2015-09-28 60 views
4

我想要获取目录的大小以及它在OS X上使用Swift的内容。到目前为止,我只能获得目录本身的大小,而没有任何内容。对于我的大多数目录,它通常显示6,148字节的值,但它确实是varie。如何在OS X上使用Swift获取目录大小

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

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

我想从这个问题上2回答,但无法确定是什么争论它需要通过斯威夫特Objective-C的功能。我相信它需要一个指针(我是一个开始学习的程序员)。

Calculate the size of a folder

我不能从这里得到的斯威夫特答案,我的目的工作,要么。

How to get the file size given a path?

我使用的Xcode 7.0和运行OS X 10.10.5。

回答

11

更新:的Xcode 8.2.1•斯威夫特3.0.2

// get your directory url 
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! 
// check if the url is a directory 
if (try? documentsDirectoryURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true { 
    print("url is a folder url") 
    // lets get the folder files 
    var folderSize = 0 
    (try? FileManager.default.contentsOfDirectory(at: documentsDirectoryURL, includingPropertiesForKeys: nil))?.lazy.forEach { 
     folderSize += (try? $0.resourceValues(forKeys: [.totalFileAllocatedSizeKey]))?.totalFileAllocatedSize ?? 0 
    } 
    // format it using NSByteCountFormatter to display it properly 
    let byteCountFormatter = ByteCountFormatter() 
    byteCountFormatter.allowedUnits = .useBytes 
    byteCountFormatter.countStyle = .file 
    let folderSizeToDisplay = byteCountFormatter.string(for: folderSize) ?? "" 
    print(folderSizeToDisplay) // "X,XXX,XXX bytes" 
} 

如果你想包括您需要使用enumeratorAtURL如下所有子文件夹,隐藏文件和文件包的后裔:

// get your directory url 
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! 
// check if the url is a directory 
if (try? documentsDirectoryURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true { 
    var folderSize = 0 
    (FileManager.default.enumerator(at: documentsDirectoryURL, includingPropertiesForKeys: nil)?.allObjects as? [URL])?.lazy.forEach { 
     folderSize += (try? $0.resourceValues(forKeys: [.totalFileAllocatedSizeKey]))?.totalFileAllocatedSize ?? 0 
    } 
    let byteCountFormatter = ByteCountFormatter() 
    byteCountFormatter.allowedUnits = .useBytes 
    byteCountFormatter.countStyle = .file 
    let sizeToDisplay = byteCountFormatter.string(for: folderSize) ?? "" 
    print(sizeToDisplay) // "X,XXX,XXX bytes" 
} 
+0

有低于2个的屏幕截图。我无法获得大小匹配。 My Documents目录是〜1.50绿带 https://drive.google.com/file/d/0B8F7IPsTUK7gUEVzeU5JRTF0Qms/view?usp=sharing 但控制台只报告272个字节 https://drive.google。 com/file/d/0B8F7IPsTUK7gaDBiZkdfREZhWkE/view?usp = sharing – JackVaughn

+0

它是本地文件夹吗? –

+0

就是这样。对我的代码进行的唯一更改是打印文档url,以确保它是正确的。 – JackVaughn

2

斯威夫特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 
} 

输出值为兆字节。 从源转换:https://gist.github.com/rayfix/66b0a822648c87326645

+1

请注意,您还需要(从源代码引用):枚举FileErrors:错误{ 情况下BadEnumeration 情况下BadResource } –

+0

我添加了错误类型枚举也。 Thx丹 –

2

夫特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 

}