查找文件大小
在我的 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];
In my iPhone app I am using the following code to find a file's size. Even though the file exists, I am seeing zero for the size.
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个;
请注意,fileSize 不一定适合整数(尤其是带符号的整数),但对于 iOS,您当然可以将其降至 long,因为实际上您永远不会超过该值。该示例使用 long long,因为在我的代码中我必须与具有更大可用存储空间的系统兼容。
Try this;
Note that the fileSize won't necessarily fit in an integer (especially a signed one) although you could certainly drop to a long for iOS as you'll never exceed that in reality. The example uses long long as in my code I have to be compatible with systems with much larger storage available.
Swift 中的一个班轮:
One liner in Swift:
如果您有
URL
(NSURL
,而不是String
),则无需使用FileManager
即可获取文件大小:If you have a
URL
(NSURL
, not aString
), you can get the file size without aFileManager
:斯威夫特 4.x
Swift 4.x
获取文件大小(以 MB 为单位)
尝试此代码 swift
Get the file size in MB
Try This code for swift
如果您有 NSURL,则无需使用 NSFileManager 即可使用
resourceValuesForKeys:error:
:(ObjC 答案灵感来自 kelin 的 Swift 答案)
If you have an
NSURL
, you can get the file size without anNSFileManager
usingresourceValuesForKeys:error:
:(ObjC answer inspired by kelin's Swift answer)