五.oc文件操作
// 1.获取程序的Home目录 NSString *homeDirectory = NSHomeDirectory(); NSLog(@"path:%@", homeDirectory); // 2.获取document目录 NSArray *paths00 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path00 = [paths00 objectAtIndex:0]; NSLog(@"path:%@", path00); // 3、获取Cache目录 NSArray *paths01 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *path01 = [paths01 objectAtIndex:0]; NSLog(@"%@", path01); // 4、获取Library目录 NSArray *paths02 = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *path02 = [paths02 objectAtIndex:0]; NSLog(@"%@", path02); // 5、获取Tmp目录 NSString *tmpDir = NSTemporaryDirectory(); NSLog(@"%@", tmpDir); // 6、写入文件 NSArray *paths06 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir06 = [paths06 objectAtIndex:0]; if (!docDir06) { NSLog(@"Documents 目录未找到"); } NSArray *array06 = [[NSArray alloc] initWithObjects:@"内容",@"content",nil]; NSString *filePath06 = [docDir06 stringByAppendingPathComponent:@"testFile.txt"]; [array06 writeToFile:filePath06 atomically:YES]; // <?xml version="1.0" encoding="UTF-8"?> // <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> // <plist version="1.0"> // <array> // <string>内容</string> // <string>content</string> // </array> // </plist> // 7、读取文件 NSArray *paths07 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir07 = [paths07 objectAtIndex:0]; NSString *filePath07 = [docDir07 stringByAppendingPathComponent:@"testFile.txt"]; NSArray *array07 = [[NSArray alloc]initWithContentsOfFile:filePath07]; NSLog(@"%@", array07); // 1、在Documents里创建目录 NSArray *paths11 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory11 = [paths11 objectAtIndex:0]; NSLog(@"documentsDirectory%@",documentsDirectory11); NSFileManager *fileManager11 = [NSFileManager defaultManager]; NSString *testDirectory = [documentsDirectory11 stringByAppendingPathComponent:@"test"]; // 创建目录 [fileManager11 createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil]; // 2、在test目录下创建文件 NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test00.txt"]; NSString *testPath2 = [testDirectory stringByAppendingPathComponent:@"test22.txt"]; NSString *testPath3 = [testDirectory stringByAppendingPathComponent:@"test33.txt"]; NSString *string = @"写入内容,write String"; [fileManager11 createFileAtPath:testPath contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; [fileManager11 createFileAtPath:testPath2 contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; [fileManager11 createFileAtPath:testPath3 contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; // 3、获取目录列里所有文件名,两种方法获取:subpathsOfDirectoryAtPath 和 subpathsAtPath NSArray *paths13 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory13 = [paths13 objectAtIndex:0]; NSLog(@"documentsDirectory%@",documentsDirectory13); NSFileManager *fileManage = [NSFileManager defaultManager]; NSString *myDirectory = [documentsDirectory13 stringByAppendingPathComponent:@"test"]; NSArray *file = [fileManage subpathsOfDirectoryAtPath: myDirectory error:nil]; NSLog(@"%@",file); NSArray *files = [fileManage subpathsAtPath: myDirectory ]; NSLog(@"%@",files); // 4、fileManager使用操作当前目录 //创建文件管理器 NSFileManager *fileManager14 = [NSFileManager defaultManager]; NSArray *paths14 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory14 = [paths14 objectAtIndex:0]; //更改到待操作的目录下 [fileManager14 changeCurrentDirectoryPath:[documentsDirectory14 stringByExpandingTildeInPath]]; //创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil NSString * fileName = @"testFileNSFileManager.txt"; NSArray *array14 = [[NSArray alloc] initWithObjects:@"hello world",@"hello world1", @"hello world2",nil]; [fileManager14 createFileAtPath:fileName contents:array14 attributes:nil]; // 5、删除文件,接上面的代码,remove就ok了。 [fileManager14 removeItemAtPath:fileName error:nil]; // 6、混合数据的读写,用NSMutableData创建混合数据,然后写到文件里。并按数据的类型把数据读出来 // 6.1写入数据 NSString * fileName16 = @"testFileNSFileManager.txt"; NSArray *paths16 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory16 = [paths16 objectAtIndex:0]; //获取文件路径 NSString *path = [documentsDirectory16 stringByAppendingPathComponent:fileName16]; //待写入的数据 NSString *temp = @"nihao 世界"; int dataInt = 1234; float dataFloat = 3.14f; //创建数据缓冲 NSMutableData *writer = [[NSMutableData alloc] init]; //将字符串添加到缓冲中 [writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]]; //将其他数据添加到缓冲中 [writer appendBytes:&dataInt length:sizeof(dataInt)]; [writer appendBytes:&dataFloat length:sizeof(dataFloat)]; //将缓冲的数据写入到文件中 [writer writeToFile:path atomically:YES]; // 6.2读取刚才写入的数据: //读取数据: int intData; float floatData = 0.0; NSString *stringData; NSData *reader = [NSData dataWithContentsOfFile:path]; stringData = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])] encoding:NSUTF8StringEncoding]; [reader getBytes:&intData range:NSMakeRange([temp length], sizeof(intData))]; [reader getBytes:&floatData range:NSMakeRange([temp length] + sizeof(intData), sizeof(floatData))]; NSLog(@"stringData:%@ intData:%d floatData:%f", stringData, intData, floatData); // bundle是一个目录,其中包含了程序会使用到的资源.这些资源包含了如图像,声音,编译好的代码,nib文件(用户也会把bundle称为plug-in).对应bundle, // cocoa提供了类NSBundle. // 我们现在用bundle获取程序里的一张图片,并显示到View上。 // 新建一个Single View Application,并在加入viewDidLoad方法里加入如下代码: // 通过使用下面的方法得到程序的main bundle NSBundle *mainBundle = [NSBundle mainBundle]; NSString *imagePath = [mainBundle pathForResource:@"QQ20120616-1" ofType:@"png"]; NSLog(@"%@", imagePath); UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; [self.view addSubview:imageView];
1. NSFileManager的使用
文件和文件夹的创建、删除、改变、遍历,读取等操作
2. NSFileHandle的使用
3. 如何获取沙盒路径
4. NSURL的使用
5. NSBundle的使用
1. NSFileManager的使用:文件和文件夹的创建、删除、改变、遍历,读取等操作
题目1.在自己的电脑上创建一个文件夹名字叫做myDir,再在里面创建一个文件myfile.txt,再将这个文件复制到文稿当中。
1.File.h
2.File.m
3.main.m
运行结果:
注意⚠️:others文件夹不存在时则复制失败,文件找不到复制后的地址
创建others文件夹后运行结果:
援引: http://blog.csdn.net/totogo2010/article/details/7670417
NSError *error = nil; NSDate *creationDate = [[NSDate alloc]init]; for (int i = 0; i < file.count; i++) { NSLog(@"\n\n文件名:%@",file[i]); NSString *everyFilePath = [NSString stringWithFormat:@"%@/%@",filePath,file[i]]; NSLog(@"路径:%@",everyFilePath); NSDictionary *fileAttributes = [fileManage attributesOfItemAtPath:everyFilePath error:&error]; if (fileAttributes) { if ((creationDate = [fileAttributes objectForKey:NSFileCreationDate])) { NSDateFormatter *format = [[NSDateFormatter alloc] init]; format.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSString *newString = [format stringFromDate:creationDate]; NSLog(@"文件创建时间 : %@\n\n", newString); } } }
/**
输入文件路径,得到排序好的相关数组,可以设置升序或降序
@param path 文件列表路径
@param isascending 是否升序
@return 排序好的数组
*/
-(NSMutableArray *)visitDirectoryList:(NSString *)path Isascending:(BOOL)isascending {
NSArray *fileList = [[NSFileManager defaultManager] subpathsAtPath:path]; // 取得目录下所有文件列表
fileList = [fileList sortedArrayUsingComparator:^(NSString *firFile, NSString *secFile) { // 将文件列表排序
NSString *firPath = [path stringByAppendingPathComponent:firFile]; // 获取前一个文件完整路径
NSString *secPath = [path stringByAppendingPathComponent:secFile]; // 获取后一个文件完整路径
NSDictionary *firFileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:firPath error:nil]; // 获取前一个文件信息
NSDictionary *secFileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:secPath error:nil]; // 获取后一个文件信息
id firData = [firFileInfo objectForKey:NSFileCreationDate]; // 获取前一个文件创建时间
id secData = [secFileInfo objectForKey:NSFileCreationDate]; // 获取后一个文件创建时间
if (isascending) {
return [firData compare:secData]; // 升序
} else {
return [secData compare:firData]; // 降序
}
}];
//______________________________________________________________________________________________________
// 将所有文件按照日期分成数组
NSMutableArray *listArray = [NSMutableArray new];//最终数组
NSMutableArray *tempArray = [NSMutableArray new];//每天文件数组
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = @"yyyy-MM-dd";
for (NSString *fileName in fileList) {
NSString *filePath = [path stringByAppendingPathComponent:fileName];
NSDictionary *fileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; // 获取文件信息
NSMutableDictionary *fileDic = [NSMutableDictionary new];
fileDic[@"Name"] = fileName;//文件名字
fileDic[NSFileSize] = fileInfo[NSFileSize];//文件大小
fileDic[NSFileCreationDate] = fileInfo[NSFileCreationDate];//时间
if (tempArray.count > 0) { // 获取日期进行比较, 按照 XXXX 年 XX 月 XX 日来装数组
NSString *currDate = [format stringFromDate:fileInfo[NSFileCreationDate]];
NSString *lastDate = [format stringFromDate:tempArray.lastObject[NSFileCreationDate]];
if (![currDate isEqualToString:lastDate]) {
[listArray addObject:tempArray];
tempArray = [NSMutableArray new];
}
}
[tempArray addObject:fileDic];
}
if (tempArray.count > 0) { // 装载最后一个 array 数组
[listArray addObject:tempArray];
}
NSLog(@"visitDirectoryList = %@", listArray);
return listArray;
}