//对于错误信息
NSError *error;
// 创建文件管理器
NSFileManager *fileMgr = [NSFileManager defaultManager];
//指向文件目录
NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//创建一个目录
[[NSFileManager defaultManager] createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] withIntermediateDirectories:YES attributes:nil error:&error];
/** < 创建一个文件*/
// File we want to create in the documents directory我们想要创建的文件将会出现在文件目录中
// Result is: /Documents/file1.txt结果为:/Documents/file1.txt
NSString *filePath= [documentsDirectory stringByAppendingPathComponent:@"file1.txt"];
//需要写入的字符串
NSString *str= @"iPhoneDeveloper Tips\nhttp://iPhoneDevelopTips,com";
//写入文件
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
//显示文件目录的内容
NSLog(@"Documentsdirectory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
/** < 对一个文件重命名*/
//通过移动该文件对文件重命名
NSString *filePath2= [documentsDirectory stringByAppendingPathComponent:@"file2.txt"];
//判断是否移动
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)
NSLog(@"Unable to move file: %@", [error localizedDescription]);
//显示文件目录的内容
NSLog(@"Documentsdirectory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
/** < 删除一个文件*/
//在filePath2中判断是否删除这个文件
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES)
NSLog(@"Unable to delete file: %@", [error localizedDescription]);
//显示文件目录的内容
NSLog(@"Documentsdirectory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
/** < 获取一个目录内的文件及文件夹列表*/
NSFileManager *fileManager = [NSFileManager defaultManager];
//在这里获取应用程序Documents文件夹里的文件及文件夹列表
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
NSError *error2 = nil;
NSArray *fileList = [[NSArray alloc] init];
//fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error2];
/** < 列出给定一个文件夹里的所有子文件夹名*/
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);