在Swift中获取文件大小

时间:2015-02-01 21:29:06

标签: ios swift

我尝试了几种方法来获取文件大小,但始终为零。

let path = NSBundle.mainBundle().pathForResource("movie", ofType: "mov")
let attr = NSFileManager.defaultManager().attributesOfFileSystemForPath(path!, error: nil)
if let attr = attr {
    let size: AnyObject? = attr[NSFileSize]
    println("File size = \(size)")
}

我进入日志:File size = nil

12 个答案:

答案 0 :(得分:98)

使用attributesOfItemAtPath代替attributesOfFileSystemForPath +在你的attr上调用.fileSize()。

var filePath: NSString = "your path here"
var fileSize : UInt64
var attr:NSDictionary? = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: nil)
if let _attr = attr {
    fileSize = _attr.fileSize();
}

在Swift 2.0中,我们使用do try catch pattern,如下所示:

let filePath = "your path here"
var fileSize : UInt64 = 0

do {
    let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)

    if let _attr = attr {
        fileSize = _attr.fileSize();
    }
} catch {
    print("Error: \(error)")
}

在Swift 3.x / 4.0中:

let filePath = "your path here"
var fileSize : UInt64

do {
    //return [FileAttributeKey : Any]
    let attr = try FileManager.default.attributesOfItem(atPath: filePath)
    fileSize = attr[FileAttributeKey.size] as! UInt64

    //if you convert to NSDictionary, you can get file size old way as well.
    let dict = attr as NSDictionary
    fileSize = dict.fileSize()
} catch {
    print("Error: \(error)")
}

答案 1 :(得分:16)

SWIFT 3 来自@ Hoa的回答,加上一个让UInt64成为可读字符串的函数。

func sizeForLocalFilePath(filePath:String) -> UInt64 {
    do {
        let fileAttributes = try FileManager.default.attributesOfItem(atPath: filePath)
        if let fileSize = fileAttributes[FileAttributeKey.size]  {
            return (fileSize as! NSNumber).uint64Value
        } else {
            print("Failed to get a size attribute from path: \(filePath)")
        }
    } catch {
        print("Failed to get file attributes for local path: \(filePath) with error: \(error)")
    }
    return 0
}
func covertToFileString(with size: UInt64) -> String {
    var convertedValue: Double = Double(size)
    var multiplyFactor = 0
    let tokens = ["bytes", "KB", "MB", "GB", "TB", "PB",  "EB",  "ZB", "YB"]
    while convertedValue > 1024 {
        convertedValue /= 1024
        multiplyFactor += 1
    }
    return String(format: "%4.2f %@", convertedValue, tokens[multiplyFactor])
}

答案 2 :(得分:12)

Swift4:轻松访问文件属性的URL扩展

扩展:

extension URL {
    var attributes: [FileAttributeKey : Any]? {
        do {
            return try FileManager.default.attributesOfItem(atPath: path)
        } catch let error as NSError {
            print("FileAttribute error: \(error)")
        }
        return nil
    }

    var fileSize: UInt64 {
        return attributes?[.size] as? UInt64 ?? UInt64(0)
    }

    var fileSizeString: String {
        return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
    }

    var creationDate: Date? {
        return attributes?[.creationDate] as? Date
    }
}

用法:

let fileUrl: URL
print("file size = \(fileUrl.fileSize), \(fileUrl.fileSizeString)")

答案 3 :(得分:9)

以下是Biodave的答案,正确的文件管理器调用

func sizeForLocalFilePath(filePath:String) -> UInt64 {
    do {
        let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)
        if let fileSize = fileAttributes[NSFileSize]  {
            return (fileSize as! NSNumber).unsignedLongLongValue
        } else {
            print("Failed to get a size attribute from path: \(filePath)")
        }
    } catch {
        print("Failed to get file attributes for local path: \(filePath) with error: \(error)")
    }
    return 0
}

答案 4 :(得分:6)

试试这个。

null

答案 5 :(得分:6)

在Swift 3+中,您可以直接从URL获取文件大小,不需要(NS)FileManagerByteCountFormatter是一种显示文件大小的智能方法。

let url = Bundle.main.url(forResource:"movie", withExtension: "mov")!
do {
    let resourceValues = try url.resourceValues(forKeys: [.fileSizeKey])
    let fileSize = resourceValues.fileSize!
    print("File size = " + ByteCountFormatter().string(fromByteCount: Int64(fileSize)))
} catch { print(error) }

实际上即使在Swift 2中也可以从URL获取文件大小,但语法有点麻烦。

答案 6 :(得分:5)

以下是使用 Swift 4 的另外两个不同的实现,一个是详细格式化的,另一个是十进制格式。

NumberFomatter

func fileSize(fromPath path: String) -> String? {
    var size: Any?
    do {
        size = try FileManager.default.attributesOfItem(atPath: path)[FileAttributeKey.size]
    } catch (let error) {
        print("File size error: \(error)")
        return nil
    }
    guard let fileSize = size as? UInt64 else {
        return nil
    }

    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.formatterBehavior = .behavior10_4
    return formatter.string(from: NSNumber(value: fileSize))
}

另一个是用大小单位定义:

func fileSize(fromPath path: String) -> String? {
    guard let size = try? FileManager.default.attributesOfItem(atPath: path)[FileAttributeKey.size],
        let fileSize = size as? UInt64 else {
        return nil
    }

    // bytes
    if fileSize < 1023 {
        return String(format: "%lu bytes", CUnsignedLong(fileSize))
    }
    // KB
    var floatSize = Float(fileSize / 1024)
    if floatSize < 1023 {
        return String(format: "%.1f KB", floatSize)
    }
    // MB
    floatSize = floatSize / 1024
    if floatSize < 1023 {
        return String(format: "%.1f MB", floatSize)
    }
    // GB
    floatSize = floatSize / 1024
    return String(format: "%.1f GB", floatSize)
}

答案 7 :(得分:4)

Swift 4解决方案: 此函数返回MB大小。

func sizePerMB(url: URL?) -> Double {
    guard let filePath = url?.path else {
        return 0.0
    }
    do {
        let attribute = try FileManager.default.attributesOfItem(atPath: filePath)
        if let size = attribute[FileAttributeKey.size] as? NSNumber {
            return size.doubleValue / 1000000.0
        }
    } catch {
        print("Error: \(error)")
    }
    return 0.0
}

答案 8 :(得分:1)

在Swift 3.0中尝试以下操作:

let fileSize = try! FileManager.default.attributesOfItem(atPath: "/bin/bash")[FileAttributeKey.size] as! Int

甚至更好:

let fileSize = (try! FileManager.default.attributesOfItem(atPath: "/bin/bash")[FileAttributeKey.size] as! NSNumber).uint64Value

答案 9 :(得分:1)

其他一些答案的启发。

 // 1. Create request message with the URL for the trending API.
string requestUrl = "https://graph.microsoft.com/V1.0/me/findMeetingTimes";
HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);

// 2. Authenticate (add access token) our HttpRequestMessage
graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm).GetAwaiter().GetResult();

// 3. Send the request and get the response.
HttpResponseMessage response = graphClient.HttpProvider.PostAsync(hrm).Result;

// 4. Get the response.
var content = response.Content.ReadAsStringAsync().Result;
JObject responseBody = JObject.Parse(content);

// 4. Get the array of objects from the 'value' key.
JToken arrayOfObjects = responseBody.GetValue("value");

答案 10 :(得分:1)

Swift中的URL扩展名以获取文件大小(如果有)。

public extension URL {

    var fileSize: Int? {
        let value = try? resourceValues(forKeys: [.fileSizeKey])
        return value?.fileSize
    }
}

返回可选Int的原因是,未知文件大小不能视为大小为零。

答案 11 :(得分:0)

这是一个紧凑版本,通过Xcode7在Swift 2.0 for iOS9中编写为快乐方法:

func sizeForLocalFilePath(filePath:String) -> UInt64 {
    do {
        let fileAttributes = try NSFileManager().attributesOfFileSystemForPath(filePath)
        if let fileSize = fileAttributes[NSFileSystemSize] as? UInt64 {
            return fileSize
        } else {
            print("Failed to get a size attribute from path: \(filePath)")
        }
    } catch {
        print("Failed to get file attributes for local path: \(filePath) with error: \(error)")
    }
    return 0
}

享受!