在我的 iPhone 应用程序中,我使用以下代码来查找文件的大小。即使文件存在,我看到的大小为零。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *URL = [documentsDirectory stringByAppendingPathComponent:@"XML/Extras/Approval.xml"];
NSLog(@"URL:%@", URL);
NSError *attributesError = nil;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];
int fileSize = [fileAttributes fileSize];
试试这个;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
请注意,文件大小不一定适合整数(尤其是带符号的整数),尽管对于 iOS,您当然可以将其降至 long,因为实际上您永远不会超过该值。该示例使用 long long,因为在我的代码中我必须与具有更大可用存储空间的系统兼容。
Swift 中的一个班轮:
let fileSize = try! NSFileManager.defaultManager().attributesOfItemAtPath(fileURL.path!)[NSFileSize]!.longLongValue
如果您有
URL
(NSURL
,而不是 String
),则无需 FileManager
即可获取文件大小:
let attributes = try? myURL.resourceValues(forKeys: Set([.fileSizeKey]))
let fileSize = attributes?.fileSize // Int?
斯威夫特 4.x
do {
let fileSize = try (FileManager.default.attributesOfItem(atPath: filePath) as NSDictionary).fileSize()
print(fileSize)
} catch let error {
print(error)
}
获取文件大小(以MB为单位) 试试这个代码 swift
func getSizeOfFile(withPath path:String) -> UInt64?
{
var totalSpace : UInt64?
var dict : [FileAttributeKey : Any]?
do {
dict = try FileManager.default.attributesOfItem(atPath: path)
} catch let error as NSError {
print(error.localizedDescription)
}
if dict != nil {
let fileSystemSizeInBytes = dict![FileAttributeKey.systemSize] as! NSNumber
totalSpace = fileSystemSizeInBytes.uint64Value
return (totalSpace!/1024)/1024
}
return nil
}