[英]How To Get Directory Size With Swift On OS X
我正在嘗試使用 Swift 獲取目錄的大小以及它在 OS X 上的內容。 到目前為止,我只能獲得目錄本身的大小,沒有任何內容。 對於我的大多數目錄,它通常顯示 6,148 字節的值,但它確實有所不同。
我已經從下面的文件中嘗試了 directorySize() function 但它也返回了 6,148 個字節。
我嘗試了這個問題的前 2 個答案,但不確定它需要什么參數將 Swift 傳遞給 Objective-C function。 我相信它需要一個指針(我是一個正在學習的初級程序員)。
而且我也無法從這里獲得 Swift 答案來滿足我的目的。
我正在使用 Xcode 7.0 並運行 OS X 10.10.5。
更新: 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)
}
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
}
Output 值是兆字節。 從源轉換: https://gist.github.com/rayfix/66b0a822648c87326645
對於正在尋找 Swift 5+ 和 Xcode 11+ 解決方案的任何人,請查看此要點
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
}
對於任何尋找准系統實現的人(在 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
),並且結果以其本機格式返回(字節為整數)。
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
}
基於https://stackoverflow.com/a/32814710/2178888答案,我使用現代 swift 並發創建了一個類似的版本。
編輯:在此處添加代碼的主要部分。 此要點中的完整版本(復制/粘貼到游樂場): 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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.