- NSFileManager 是用来管理文件系统的,常用来操作文件/文件夹
NSFileManager使用了单列模式,通过 [NSFileManager defaultManager] 来获取单列
- -(BOOL)fileExistsAtPath:(NSString *)path ;判断文件或文件夹是否存在
NSFileManager *mgr = [NSFileManager defaultManager];
BOOL exist = [mgr fileExistsAtPath:@"/Users/apple/Desktop/test.txt"];
NSLog(@"文件是否存在:%d ", exist);
- -(BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory; 判断文件\文件夹是否存在, isDirectory代表是否为文件夹
NSFileManager *mgr = [NSFileManager defaultManager];
// 默认不是文件夹
BOOL dir = NO;
BOOL exist = [mgr fileExistsAtPath:@"/Users/apple/Desktop/flows" isDirectory:&dir];
NSLog(@"文件是否存在:%d, 是否为文件夹:%d", exist, dir);
- -(NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error 获得path这个文件\文件夹的属性
NSFileManager *mgr = [NSFileManager defaultManager];
// 获得文件、文件夹的属性
NSDictionary *attrs = [mgr attributesOfItemAtPath:@"/Users/apple/Desktop/test.txt" error:nil];
NSLog(@"%@", attrs[NSFileSize]);
result@2x.png
- -(NSArray *)subpathsAtPath:(NSString *)path; 获得path的所有子路径
NSFileManager *mgr = [NSFileManager defaultManager];
// 获得当前文件夹下面有哪些内容
NSArray *contents = [mgr contentsOfDirectoryAtPath:@"/Users/apple/Desktop/共享课堂/02-OC语法加强" error:nil];
NSLog(@"%@", subpaths);
output@2x.png
- -(NSArray *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error ,获得path的所有子路径
NSFileManager *mgr = [NSFileManager defaultManager];
// 获得当前文件夹下面有哪些内容
NSArray *subpaths = [mgr subpathsOfDirectoryAtPath:@"/Users/apple/Desktop/共享课堂/02-OC语法加强" error:nil];
NSLog(@"%@", subpaths);
QQ20180426-235149@2x.png
- -(BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error; 创建文件夹
NSFileManager *mgr = [NSFileManager defaultManager];
// 创建文件夹
// Intermediate 中间的、中间产物
// withIntermediateDirectories : 如果是YES,代表会自动创建所有的文件夹
[mgr createDirectoryAtPath:@"/Users/apple/Desktop/test/abc/itcast" withIntermediateDirectories:YES attributes:nil error:nil];
- -(BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr; 创建文件
NSFileManager *mgr = [NSFileManager defaultManager];
// 创建文件夹
// Intermediate 中间的、中间产物
// withIntermediateDirectories : 如果是YES,代表会自动创建所有的文件夹
[mgr createDirectoryAtPath:@"/Users/apple/Desktop/test/abc/itcast" withIntermediateDirectories:YES attributes:nil error:nil];
// NSData : 存放二进制字节数据
NSString *str = @"爆发后就开始客户机房环境快递顺丰快回家";
// NSString --> NSData
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[mgr createFileAtPath:@"/Users/apple/Desktop/itcast.mp3" contents:data attributes:nil];
获取文件夹的size
//参考sdwebimage
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
for (NSString *fileName in fileEnumerator)
NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
size += [attrs fileSize];
网友评论