A. 目录管理
NSFileManager*manager = [NSFileManagerdefaultManager];//单例模式 // 1.获取文件属性
NSString *path = @"/Users/hellovoidworld/desktop/oc/test20141121.txt";
NSFileManager *manager = [NSFileManagerdefaultManager]; // 单例模式
NSDictionary *attrDic = [manager attributesOfItemAtPath:path error:nil];
NSLog(@"attrDic: %@", attrDic); // 2.获得目录下的文件与子文件目录列表
NSString *dirPath = @"/Users/hellovoidworld/desktop/oc"; // 只能获取到第一级目录的文件和文件夹(名字)
NSArray *subDirArr = [manager contentsOfDirectoryAtPath:dirPath error:nil];
NSLog(@"subDirArr: %@", subDirArr); // 包含所有文件、子目录(名字)
NSArray *subPath = [manager subpathsAtPath:dirPath];
NSLog(@"subPath: %@", subPath); // 3.管理目录
// 创建目录
[manager createDirectoryAtPath:@"/Users/hellovoidworld/desktop/oc/newFolder"withIntermediateDirectories:NOattributes:nilerror:nil];
//withIntermediateDirectories 参数表示要不要创建不存在的所有目录,NO表示只能创建一级目录 // 移动目录
[manager moveItemAtPath:@"/Users/hellovoidworld/desktop/oc/newFolder/existedFolder"toPath:@"/Users/hellovoidworld/desktop/oc/newFolder/movedFolder"error:&error];
// existedFolder会被剪切变成movedFolder,移动到指定位置 // 删除目录
[manager removeItemAtPath:@"/Users/hellovoidworld/desktop/oc/newFolder/deletingFolder"error:nil]; // 拷贝文件
[manager copyItemAtPath:@"/Users/hellovoidworld/desktop/oc/newFolder/copyingFolder"toPath:@"/Users/hellovoidworld/desktop/oc/newFolder/copiedFolder"error:nil];
B.文件管理
NSFileManager *fileManager = [NSFileManager defaultManager]; // // 1.获得文件
NSString *path = @"/Users/hellovoidworld/desktop/oc/M2.jpg";
NSData *data = [NSData dataWithContentsOfFile:path]; // 提取数据
NSLog(@"%ld", data.length); NSString *path2 = @"/Users/hellovoidworld/desktop/oc/M2Copy.jpg";
[fileManager createFileAtPath:path2 contents:data attributes:nil]; // 写入数据 // 2.移动文件,相当于剪切操作
NSString *fromPath = @"/Users/hellovoidworld/desktop/oc/M2Copy.jpg";
NSString *toPath = @"/Users/hellovoidworld/desktop/oc/newFolder/M2.jpg";
[fileManager moveItemAtPath:fromPath toPath:toPath error:nil]; // 3.删除文件
[fileManager removeItemAtPath:@"/Users/hellovoidworld/desktop/oc/newFolder/M2.jpg" error:nil];
C.NSData处理数据
// NSData是一个不可变长度的Data类型,可以一次性加载文件内容
NSData *data = [NSData dataWithContentsOfFile:@"/Users/hellovoidworld/desktop/oc/newFolder/test.txt"];
NSLog(@"data length = %ld", data.length); // 利用NSData写入文件数据
[data writeToFile:@"/Users/hellovoidworld/desktop/oc/newFolder/test2.txt" atomically:YES]; // NSMutableData
NSMutableData *muData = [[NSMutableData alloc] init]; NSString *str1 = @"我要好好学习!";
NSString *str2 = @"天天向上!";
NSString *str3 = @"今天休息!"; NSDate *data1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
NSData *data2 = [str2 dataUsingEncoding:NSUTF8StringEncoding];
NSData *data3 = [str3 dataUsingEncoding:NSUTF8StringEncoding]; [muData appendData:data1];
[muData appendData:data2];
[muData appendData:data3]; NSString *muPath = @"/Users/hellovoidworld/desktop/oc/newFolder/mu.txt";
[muData writeToFile:muPath atomically:YES];