【发布时间】:2010-10-23 08:41:50
【问题描述】:
我有一个包含在 NSString 中的文件的路径。有没有办法获取它的文件大小?
【问题讨论】:
标签: objective-c cocoa macos
我有一个包含在 NSString 中的文件的路径。有没有办法获取它的文件大小?
【问题讨论】:
标签: objective-c cocoa macos
在 Swift 3.x 及更高版本中,您可以使用:
do {
//return [FileAttributeKey : Any]
let attr = try FileManager.default.attributesOfItem(atPath: filePath)
fileSize = attr[FileAttributeKey.size] as! UInt64
//or you can convert to NSDictionary, then get file size old way as well.
let attrDict: NSDictionary = try FileManager.default.attributesOfItem(atPath: filePath) as NSDictionary
fileSize = dict.fileSize()
} catch {
print("Error: \(error)")
}
【讨论】:
Swift4:
let attributes = try! FileManager.default.attributesOfItem(atPath: path)
let fileSize = attributes[.size] as! NSNumber
【讨论】:
如果你只想使用字节的文件大小,
unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:yourAssetPath error:nil] fileSize];
NSByteCountFormatter 用精确的 KB、MB、GB 对文件大小(从字节)进行字符串转换......它的返回类似于 120 MB 或 120 KB
NSError *error = nil;
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:yourAssetPath error:&error];
if (attrs) {
NSString *string = [NSByteCountFormatter stringFromByteCount:fileSize countStyle:NSByteCountFormatterCountStyleBinary];
NSLog(@"%@", string);
}
【讨论】:
它将以字节为单位给出文件大小...
uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:_filePath error:nil] fileSize];
【讨论】:
如果有人需要 Swift 版本:
let attr: NSDictionary = try! NSFileManager.defaultManager().attributesOfItemAtPath(path)
print(attr.fileSize())
【讨论】:
斯威夫特 2.2:
do {
let attr: NSDictionary = try NSFileManager.defaultManager().attributesOfItemAtPath(path)
print(attr.fileSize())
} catch {
print(error)
}
【讨论】:
这一班轮可以帮助人们:
unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize];
这会返回以字节为单位的文件大小。
【讨论】:
INT_MAX 字节会怎样?您可能希望将结果转换为 size_t 或 unsigned long long int,以便准确报告大文件 (> 2 GB) 的大小。
unsigned long long,所以int不适合在这里。
CPU raises with attributesOfItemAtPath:error:
你应该使用stat。
#import <sys/stat.h>
struct stat stat1;
if( stat([inFilePath fileSystemRepresentation], &stat1) ) {
// something is wrong
}
long long size = stat1.st_size;
printf("Size: %lld\n", stat1.st_size);
【讨论】:
stat 结构吗?
根据 Oded Ben Dov 的回答,我宁愿在这里使用一个对象:
NSNumber * mySize = [NSNumber numberWithUnsignedLongLong:[[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]];
【讨论】:
请记住,从 Mac OS X v10.5 开始不推荐使用 fileAttributesAtPath:traverseLink:。请改用attributesOfItemAtPath:error:,如same URL thesamet 所述。
请注意,我是 Objective-C 新手,我忽略了调用 attributesOfItemAtPath:error: 时可能出现的错误,您可以执行以下操作:
NSString *yourPath = @"Whatever.txt";
NSFileManager *man = [NSFileManager defaultManager];
NSDictionary *attrs = [man attributesOfItemAtPath: yourPath error: NULL];
UInt32 result = [attrs fileSize];
【讨论】: