创建一个文件并写入内容,比如在桌面上创建一个文件 lff.txt,并写入内容:My name is LFF:
NSString *str = @”My name is LFF”; NSError *error;BOOL isWritSuccess = [str writeToFile:@”/User/LFF/Desktop/lff.txt” atomically:YES encoding:NSUTF8StringEncoding error:&error];if (isWritSuccess) { NSLog(@”创建成功”); }else { NSLog(@”error %@”,error);}
通过上面代码成功创建了一个文件,下面步入正题:
1、打印文件创建日期与大小
NSFileManager * fileManager = [NSFileManager defaultManager];NSString * path = @"/ User/LFF/Desktop/lff.txt ";NSError * error;NSDictionary * dic = [fileManager attributesOfItemAtPath:path error:&error];NSLog(@"dic %@",dic); if (error == nil){ NSDate * date = [dic objectForKey:NSFileCreationDate]; NSString * size = [dic objectForKey:NSFileSize]; NSLog(@" date = %@, size = %@",date,size);}
2、获得目录下的文件与子文件目录列表
(1)获得目标目录下,第一级目录
NSFileManager * fileManager = [NSFileManager defaultManager]; NSString * path = @"/Users/aplle/Desktop/Myfile";NSError * error;NSArray * array = [fileManager contentsOfDirectoryAtPath:path error:&error];NSLog(@"array %@",array);
(2)逐级获得所有子集的目录
NSFileManager * fileManager = [NSFileManager defaultManager]; NSString * path = @"/Users/aplle/Desktop/other";NSError * error;NSArray * array = [fileManager subpathsOfDirectoryAtPath:path error:&error];NSLog(@"array %@",array);
3、管理目录
(1)创建目录NSFileManager * fileManager = [NSFileManager defaultManager];NSString * path = @"/Users/LFF/Desktop/myfolder/aaa";NSError * error;/*withIntermediateDirectories 参数:YES 逐级创建文件夹NO 表示只能够创建一级目录*/BOOL isCreateSuccess = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];if (isCreateSuccess) { NSLog(@"创建成功");}else { NSLog(@"error %@",error); }
(2)移动目录 移动就是剪切操作
NSFileManager * fileManager = [NSFileManager defaultManager];NSString * path = @"/Users/aplle/Desktop/myfolder";NSString * pathTo = @"/Users/aplle/Desktop/newmyfolder";NSError * error ;BOOL isMoveSuccess = [fileManager moveItemAtPath:path toPath:pathTo error:&error]; if (isMoveSuccess){ NSLog(@"移动成功");} else { NSLog(@"error %@",error);}
(3)删除
NSFileManager * fileManager = [NSFileManager defaultManager]; NSString * path = @"/Users/aplle/Desktop/newmyfolder"; NSError * error;BOOL isRemoveSuccess =[fileManager removeItemAtPath:path error:&error];if (isRemoveSuccess){NSLog(@"删除成功");} else {NSLog(@"erro %@",error);}
(4)拷贝文件
NSFileManager * fileManager = [NSFileManager defaultManager];NSString * path = @"/Users/aplle/Desktop/myfolder";NSString * pathTo = @"/Users/aplle/Desktop/newmyfolder";NSError * error;BOOL isCopySuccess = [fileManager copyItemAtPath:path toPath:pathTo error:&error]; if(isCopySuccess){NSLog(@"拷贝成功");} else {NSLog(@"error %@",error);}