NSFileManager中包含了用来查询单词库目录、创建、重命名、删除目录以及获取/设置文件属性的方法(可读性,可编写性等等)。
每个程序都会有它自己的沙盒,通过它你可以阅读/编写文件。
-
NSError *error;//保存错误信息 -
//创建文件管理器 NSFileManager *fileManager = [NSFileManager defaultManager]; //指向文件目录 NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathCom ponent:@"Documents"]; //指向文件目录的另一种方法
//
NSArray *paths = NSSearchPathForDirectori esInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //
NSLog(@"%d",[paths count]);//=1 //
NSString *documentsDirectory = [paths objectAtIndex:0]; NSLog(@"%@",documentsDirectory); //创建一个目录
NSString *directoryPath = [documentsDirectory stringByAppendingPathCom ponent:@"myFolder"]; [[NSFileManager defaultManager]createDirectoryAtPath:directoryPath withIntermediateDirector ies:YES attributes:nil error:nil]; //创建一个文件 NSString *filePath = [directoryPath stringByAppendingPathCom ponent:@"file.txt"]; [[NSFileManager defaultManager]createFileAtPath:filePath contents:nil attributes:nil]; //需要写入的字符串 NSString *str = @"iPhoneDeveloper Tips\nhttp://iPhoneDevelopTips,com你好"; //写入文件(文件目录必须提前创建,文件可以不必提前创建,写入文件的时候,如果没有文件会自动创建) [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; //显示文件目录的内容 NSLog(@"文件目录内容:%@",[fileManager contentsOfDirectoryAtPat h:directoryPath error:&error]); //对一个文件重命名(通过移动文件实现) NSString *filePath1 = [directoryPath stringByAppendingPathCom ponent:@"file1.txt"]; if([fileManager moveItemAtPath:filePath toPath:filePath1 error:&error]!=YES) NSLog(@"unable to move file:%@",[error localizedDescription]); //删除一个文件 if([fileManager removeItemAtPath:filePath1 error:&error]!=YES) NSLog(@"unable to remove file:%@",[error localizedDescription]); //获取应用程序Documents文件夹里的文件及文件夹列表 //fileList便是Documents文件夹下所有文件的文件名及文件夹名的数组 NSArray *fileList = [[NSArray alloc]init]; fileList = [fileManager contentsOfDirectoryAtPat h:documentsDirectory error:&error]; NSLog(@"Documents:%d,%@",[fileList count],[fileList objectAtIndex:1]); //获取某个文件夹下所有子文件夹名
NSMutableArray *dirArray = [[NSMutableArray alloc]init]; BOOL isDir = NO; for(NSString *fileName in fileList) { NSString *path = [documentsDirectory stringByAppendingPathCom ponent:fileName]; [fileManager fileExistsAtPath:path isDirectory:&isDir]; if(isDir) { [dirArray addObject:fileName]; } isDir = NO; } NSLog(@"All folders in documents:%@",dirArray);
-