查找文件大小

Kir*_*ran 56 cocoa-touch objective-c filesize nsfilemanager ios

在我的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];
Run Code Online (Sandbox Code Playgroud)

Rog*_*ger 125

试试这个;

NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];

NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
Run Code Online (Sandbox Code Playgroud)

请注意,fileSize不一定适合整数(尤其是有符号的整数),尽管你可以在iOS中使用很长时间,因为在现实中你永远不会超过它.该示例使用long long,因为在我的代码中,我必须与具有更大存储空间的系统兼容.

  • Xcode 4.5+ 单行:`long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil][NSFileSize] longLongValue]`。 (43认同)
  • 可写得更短:`unsigned long long size = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] .fileSize` (14认同)
  • 最好是`unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] [NSFileSize] unsignedLongLongValue]`因为[`NSFileSize`是一个**`unsigned`**`long long`](https:/ /developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/nsfilemanager_Class/Reference/Reference.html#//apple_ref/doc/uid/20000305-SW2). (8认同)
  • 您不能将URL作为Path参数发送.你需要发送`[URL路径]` (2认同)

Kro*_*dak 6

Swift中的一个班轮:

let fileSize = try! NSFileManager.defaultManager().attributesOfItemAtPath(fileURL.path!)[NSFileSize]!.longLongValue
Run Code Online (Sandbox Code Playgroud)

  • 更新了斯威夫特3:`让档案大小=尝试(FileManager.default.attributesOfItem(络基:url.path)[大小]为NSNumber的!).uint64Value` _or_`让档案大小=尝试(FileManager.default.attributesOfItem(络基:网址.path)as NSDictionary).fileSize()` (2认同)

kel*_*lin 6

如果您有URL( NSURL,而不是String),则可以在没有 的情况下获取文件大小FileManager

 let attributes = try? myURL.resourceValues(forKeys: Set([.fileSizeKey]))
 let fileSize = attributes?.fileSize // Int?
Run Code Online (Sandbox Code Playgroud)