-(NSString *)documentPath
{
//获得沙盒中Document的路径
NSArray *pathes = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * path = [pathes lastObject];
return path;
}
#pragma mark - NSString
-(void)writeStringToFile
{
NSString * str =@"测试字符串";
NSString * strPath = [[self documentPath]stringByAppendingString:@"/string.txt"];
NSError * error = Nil;
[str writeToFile:strPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!error) {
NSLog(@"write successfully");
}
}
-(void)readStringFromFile
{
NSString * strPath = [[self documentPath]stringByAppendingString:@"/string.txt"];
NSError * error = Nil;
NSString * str = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:&error];
if (!error) {
NSLog(@"read successfully");
NSLog(@"str == %@",str);
}else{
NSLog(@"read error");
}
}
#pragma mark - NSArray
-(void)writeArrayToFile
{
NSString * arrPath = [[self documentPath]stringByAppendingString:@"/array.txt"];
NSArray * arr = [NSArray arrayWithObjects:@"对象1",@"对象2",@"对象3",@"对象4",@"对象5", nil];
BOOL state = [arr writeToFile:arrPath atomically:YES];
if (state == YES) {
NSLog(@"write successfully");
}else{
NSLog(@"fail to write");
}
}
-(void)readArrayFromFile
{
NSString * arrPath = [[self documentPath]stringByAppendingString:@"/array.txt"];
NSArray * arr = [NSArray arrayWithContentsOfFile:arrPath];
NSLog(@"arr == %@",arr);
}
#pragma mark - NSDictionary
-(void)writeDictionaryToFile
{
NSString *dicPath =[[self documentPath]stringByAppendingString:@"/dic.txt"];
NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"yxbing",@"name",@"24",@"age",nil];
BOOL state = [dic writeToFile:dicPath atomically:YES];
if (state == YES) {
NSLog(@"write successfully");
}else{
NSLog(@"fail to write");
}
}
-(void)readDictionaryFromFile
{
NSString *dicPath =[[self documentPath]stringByAppendingString:@"/dic.txt"];
NSDictionary * dic = [NSDictionary dictionaryWithContentsOfFile:dicPath];
NSLog(@"dic == %@",dic);
}
#pragma mark - NSData
-(void)writeDataToFile
{
//NSString转化为NSData,将NSData写入文件
NSString *dataPath =[[self documentPath]stringByAppendingString:@"/data.txt"];
NSString *str = @"天道酬勤";
NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
BOOL state = [data writeToFile:dataPath atomically:YES];
if (state == YES) {
NSLog(@"write successfully");
}else{
NSLog(@"fail to write");
}
}
-(void)readDadaFromData
{
//将NSData从文件里读出来转化为NSString打印出来
NSString *dataPath =[[self documentPath]stringByAppendingString:@"/data.txt"];
NSData * data = [NSData dataWithContentsOfFile:dataPath];
//NSData转NSString只有这个方法
NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"str == %@",str);
[str release];
}
ios中NSString、NSArray、NSData、NSDictionary本地读写
最新推荐文章于 2018-12-06 15:49:09 发布