2013年12月10日学习日志:IOS沙盒机制和文件操作(2)
1. 在document里创建目录
//获取当前程序的document的路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSLog(@"当前程序的document目录%@",documentDirectory);
//创建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//myTest的路径
NSString *myTestDirectory = [documentDirectory stringByAppendingPathComponent:@"myTest"];
//创建目录
[fileManager createDirectoryAtPath:myTestDirectory withIntermediateDirectories:YES attributes:nil error:nil];
输出:2013-12-15 19:49:57.294 a[1074:c07] 当前程序的document目录/Users/haixia/Library/ApplicationSupport/iPhoneSimulator/6.1/Applications/B89BC296-EB87-4789-A497-914C3DF8FB55/Documents
2. 在刚刚创建的目录下创建文件
//在myTest目录下创建文件
//文件的路径
NSString*testPsth1 = [myTestDirectory stringByAppendingPathComponent:@"tsst1.txt"];
NSString*testPath2 = [myTestDirectory stringByAppendingPathComponent:@"test2.txt"];
NSString*testPath3 = [myTestDirectory stringByAppendingPathComponent:@"test3.txt"];
//写入的内容
NSString *string= @"hello,1234567";
//创建文件
[fileManager createFileAtPath:testPsth1contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
[fileManager createFileAtPath:testPath2contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
[fileManager createFileAtPath:testPath3contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
3. 获取目录列表里的所有文件
//获取目录列表里的所有文件
//NSArray *file = [fileManagersubpathsAtPath:myTestDirectory];
NSArray *file = [fileManager subpathsOfDirectoryAtPath:myTestDirectory error:nil];
NSLog(@"%@",file);
NSArray *files = [fileManager subpathsAtPath:myTestDirectory];
NSLog(@"%@",files);
// 2013-12-15 20:16:31.041 a[1208:c07] 当前程序的document目录/Users/haixia/Library/ApplicationSupport/iPhoneSimulator/6.1/Applications/B89BC296-EB87-4789-A497-914C3DF8FB55/Documents
// 2013-12-15 20:16:31.046 a[1208:c07] (
// ".DS_Store",
// "test2.txt",
// "test3.txt",
// "tsst1.txt"
// )
// 2013-12-15 20:16:31.047 a[1208:c07] (
// ".DS_Store",
// "test2.txt",
// "test3.txt",
// "tsst1.txt"
// )