-(long)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小 { long size = 0; NSFileManager *fileManager = [[NSFileManager alloc] init]; NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil]; for(int i = 0; i<[array count]; i++) { NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]]; BOOL isDir; if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) ) { NSDictionary *fileAttributeDic = [fileManager attributesOfItemAtPath:fullPath error:nil]; size += fileAttributeDic.fileSize; } else { [self fileSizeForDir:fullPath]; } } [fileManager release]; return size; } //单位:MB - (NSString *)sizeCache{ NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; long docSize = [self fileSizeForDir:docPath]; NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES); NSString*cachesDir = [paths objectAtIndex:0]; NSString *ImageCachePath = [cachesDir stringByAppendingPathComponent:@"ImageCache"]; NSLog(@"ImageCacheSize:%@",ImageCachePath); long ImageCacheSize = [self fileSizeForDir:ImageCachePath]; long totalSize = docSize + ImageCacheSize; const unsigned int bytes = 1024*1024 ; //字节数,如果想获取KB就1024,MB就1024*1024 NSString *string = [NSString stringWithFormat:@"%.2f",(1.0 *totalSize/bytes)]; NSLog(@"docSize:%ld,ImageCacheSize:%ld",docSize,ImageCacheSize); return string; }
在开发iPhone程序时,有时候要对文件进行一些操作。而获取某一个目录中的所有文件列表,是基本操作之一。通过下面这段代码,就可以获取一个目录内的文件及文件夹列表。
NSFileManager *fileManager = [NSFileManager defaultManager];
//在这里获取应用程序Documents文件夹里的文件及文件夹列表
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
NSError *error = nil;
NSArray *fileList = [[NSArray alloc] init];
//fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error];
以下这段代码则可以列出给定一个文件夹里的所有子文件夹名
NSMutableArray *dirArray = [[NSMutableArray alloc] init];
BOOL isDir = NO;
//在上面那段程序中获得的fileList中列出文件夹名
for (NSString *file in fileList) {
NSString *path = [documentDir stringByAppendingPathComponent:file];
[fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if (isDir) {
[dirArray addObject:file];
}
isDir = NO;
}
NSLog(@"Every Thing in the dir:%@",fileList);
NSLog(@"All folders:%@",dirArray);