我有一個包含在NSString中的文件的路徑。有沒有一種方法來獲取其文件大小?如何獲得給定路徑的文件大小?
回答
請記住fileAttributesAtPath:traverseLink:自Mac OS X v10.5起不推薦使用。改爲使用attributesOfItemAtPath:error:
,在same URL處說明。
需要提醒的是我是一個Objective-C的新手,而我忽略了可能發生的調用attributesOfItemAtPath:error:
錯誤,您可以執行以下操作:
NSString *yourPath = @"Whatever.txt";
NSFileManager *man = [NSFileManager defaultManager];
NSDictionary *attrs = [man attributesOfItemAtPath: yourPath error: NULL];
UInt32 result = [attrs fileSize];
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);
以上不應該在這裏使用fileSystemRepresentation而不是UTF8String? – 2013-01-23 11:41:12
你說得對。 HFS +爲文件名定義了標準的Unicode分解(「規範分解」)。 -UTF8String不保證返回正確的組合; -fileSystemRepresentation is。[1](http://cocoadev.com/wiki/StringWithCString) – 2013-01-28 07:11:32
@ParagBafna我知道這是一個古老的線程,但你知道我怎樣才能在swift中使用'stat'結構嗎? – 2015-06-26 22:05:38
在從俄德本多夫的答案,我寧願在這裏使用的對象:
NSNumber * mySize = [NSNumber numberWithUnsignedLongLong:[[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]];
萬一有人需要斯威夫特版本:
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)
}
它會給文件大小以字節。 ..
uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:_filePath error:nil] fileSize];
如果只想文件大小與字節只使用,文件大小(從字節)的精確KB,MB,GB
unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:yourAssetPath error:nil] fileSize];
NSByteCountFormatter字符串轉換...它的回報像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);
}
Swift4:
let attributes = try! FileManager.default.attributesOfItem(atPath: path)
let fileSize = attributes[.size] as! NSNumber
- 1. OSX:如何獲得給定文件系統的最大文件大小
- 2. 獲取文件大小給出的路徑
- 3. 獲取給定路徑的文件ID
- 4. Babel插件:如何獲得給定節點的路徑?
- 5. 如何從給定文件夾路徑獲取文件夾路徑?
- 6. 如何獲得jar文件路徑
- 7. C#:如何獲得Process.Start在給定文件時沒有路徑時將使用的可執行文件路徑?
- 8. C++:如何在該文件的路徑與給定的路徑
- 9. 如何獲得知道exe文件路徑的物理路徑?
- 10. 得到給定一個路徑和文件名路徑名
- 11. Python:如何獲得PyQt5中選定文件的文件大小?
- 12. 如何獲取給定路徑的媒體文件的ID?
- 13. 如何獲得文件路徑的手柄被鎖定
- 14. 如何獲得DataGridBoundColumn的綁定路徑
- 15. JPanel無法獲得給定的大小
- 16. 如何獲得文件大小
- 17. 如何獲得一個給定的路徑
- 18. 如何獲得給定函數的調用路徑?
- 19. 如何獲得文件大小小於500mb的文件列表?
- 20. Python的文件路徑和大小
- 21. C#中的文件路徑/大小#
- 22. PHP文件大小的直接路徑
- 23. 幫助文件夾路徑的大小
- 24. 從文件名獲得文件路徑
- 25. 如何從給定路徑獲取子文件夾名稱Server.MapPath
- 26. 獲取給定的路徑
- 27. 如何確定給定路徑是文件還是文件夾?
- 28. 如何獲得沒有文件路徑的文件名?
- 29. 我如何獲得打開文件的文件路徑?
- 30. 獲得文件大小
此代碼泄漏了分配的FileManager。我建議你簡單地使用NSFileManager.defaultManager單例來避免這種情況。 – 2012-10-18 10:07:47