?
创建与删除: ??? //创建文件管理器 ????NSFileManager *fileManager = [NSFileManager defaultManager]; ??? //获取路径 ??? //参数NSDocumentDirectory要获取那种路径 ??? NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); ??? NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径 ? ??? //更改到待操作的目录下 ??? [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]]; ? ??? //创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil ??? [fileManager createFileAtPath:@"fileName" contents:nil attributes:nil]; ? ??? //删除待删除的文件 ??? [fileManager removeItemAtPath:@"createdNewFile" error:nil]; ? 写入数据: ???//获取文件路径 ???NSString *path = [documentsDirectory stringByAppendingPathComponent:@"fileName"]; ? ????//待写入的数据 ??? NSString *temp = @"Hello friend"; ??? int data0 = 100000; ??? float data1 = 23.45f; ? ????//创建数据缓冲 ??? NSMutableData *writer = [[NSMutableData alloc] init]; ? ????//将字符串添加到缓冲中 ??? [writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]]; ? ????//将其他数据添加到缓冲中 ??? [writer appendBytes:&data0 length:sizeof(data0)]; ??? [writer appendBytes:&data1 length:sizeof(data1)]; ? ? ????//将缓冲的数据写入到文件中 ??? [writer writeToFile:path atomically:YES]; ??? [writer release]; ? ? 读取数据: ??? int gData0; ??? float gData1; ??? NSString *gData2; ? ??? NSData *reader = [NSData dataWithContentsOfFile:path]; ??? gData2 = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])] ??? ??? ??? ??? ??? ??? ??? ??? ? encoding:NSUTF8StringEncoding]; ??? [reader getBytes:&gData0 range:NSMakeRange([temp length], sizeof(gData0))]; ??? [reader getBytes:&gData2 range:NSMakeRange([temp length] + sizeof(gData0), sizeof(gData1))]; ? ??? NSLog(@"gData0:%@? gData1:%i gData2:%f", gData0, gData1, gData2); ? ? 读取工程中的文件: 读取数据时,要看待读取的文件原有的文件格式,是字节码还是文本,我经常需要重文件中读取字节码,所以我写的是读取字节文件的方式。 ??? //用于存放数据的变量,因为是字节,所以是UInt8 ??? UInt8 b = 0; ? ??? //获取文件路径 ??? NSString *path = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@""]; ? ?? //获取数据? ?? NSData *reader = [NSData dataWithContentsOfFile:path]; ? ?? //获取字节的个数 ??? int length = [reader length]; ??? NSLog(@"------->bytesLength:%d", length); ??? for(int i = 0; i < length; i++) ??? { ??????? //读取数据 ??? ??? [reader getBytes:&b range:NSMakeRange(i, sizeof(b))]; ??? ??? NSLog(@"-------->data%d:%d", i, b);???? ? ??? } ? |