iphone-文件操作初步理解

NSData:自定义文件格式,可以处理各种类型的数据
NSDictionary:键-值对,处理plist文件,xml格式,为了保密,也可以存入经过NSData处理过的数据
NSData用法:
1.写入文件
//文件路径:根目录iphonefile文件夹
NSString *path = @"/iphonefile/datatest.dat";

NSString *tempStr = @"hello iphone";

int int_test = 15;

float f_test = 35.0f;

NSMutableData *writerData = [[NSMutableData alloc] init];
//字符串
[writer appendData:[tempStr dataUsingEncoding:NSUTF8StringEncoding]];

//int数据
[writerData appendBytes:&int_test length:sizeof(int_test)];

//float数据

[writerData appendBytes:&f_test length:sizeof(f_test)];

//写入文件

[writerData writeToFile:path atomically:YES];

//释放
writerData = nil;

[writerData release];

 


2.读取刚才写入的文件


int int_read;

float f_read;

NSString *strRead;

NSData *readerData = [NSData dataWithContentsOfFile:path];

//读取字符串
strRead = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [tempStr length])] encoding:NSUTF8StringEncoding];

//读取int

[reader getBytes:&int_read range:NSMakeRange([tempStr length], sizeof(int_read))];

//读取float

[reader getBytes:&f_read range:NSMakeRange([tempStr length] + sizeof(int_read), sizeof(f_read))];

NSLog(@"string=:%@  int_read=:%i f_read=:%f", strRead, int_read, f_read);

//释放
readerData = nil;
[readerData release];


NSDictionary用法:

1.写入数据到plist文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

 NSString *documentsDirectory = [paths objectAtIndex:0];

//文件路径或者直接用~表示当前应用的目录

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"test.plist"]; 

 

NSMutableDictionary* dict_rank = nil;

 NSFileManager *fileManager = [NSFileManager defaultManager];

 //文件不存在则创建文件

 if(![fileManager fileExistsAtPath:filePath]){

  NSLog(@"file not exist");

  dict_rank = [[NSMutableDictionary alloc] init];

  [dict_rank writeToFile:filePath atomically:YES];

 }

//key-value  (temp-abcdef)

 

[dict_rank setObject:[@"abcdef" dataUsingEncoding:NSUTF8StringEncoding] forKey:@"temp"];

[dcit_rank setObject:@"valu" forKey:@"key"];

//写入经过NSData处理的数据


NSMutableData* write = [[NSMutableData alloc] init];

int key_num = 16;

[write appendBytes:&key_num length:sizeof(key_num)];

[dict_rank setObject:write forKey:@"knum"];

[dict_rank setObject:@"me" forKey:@"who"]

 

[dict_rank writeToFile:filePath atomically:YES];

 

 

2.读取plist文件
dict_rank = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSData* tt = [dict_rank valueForKey:@"temp"];

 //[tt subdataWithRange:NSMakeRange(0, 4)]

 NSString* ttemp22 = [[NSString alloc] initWithData:tt

          encoding:NSUTF8StringEncoding]; 

 

NSLog(@"ttemp22=%s     ",[ttemp22 UTF8String]);


NSData * ia = [dict_rank valueForKey:@"knum"] ;

 int ttemp33 ;

 [ia getBytes:&ttemp33];

NSString* strWho = [dict_rank valueForKey:@"who"];

 

 

来源:http://blog.csdn.net/ccdxwjw/archive/2008/12/23/3590519.aspx

你可能感兴趣的:(String,File,iPhone,Path,float,encoding)