//*********写入文件,传入要保存的信息*********//保存xml
-(void) saveXml:(NSString *)data
{
//创建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager ];
//获取路径
//参数NSDocumentDirectory要获取那种路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"paths=%@",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径
NSLog(@"documentsDirectory=%@",documentsDirectory);
//更改到待操作的目录下
NSLog(@"[documentsDirectory stringByExpandingTildeInPath]=%@",[documentsDirectory stringByExpandingTildeInPath]);
[fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
//创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil
//获取文件路径
[fileManager removeItemAtPath:@"username"error:nil];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"cc.txt"];
NSLog(@"path=%@",path);
//创建数据缓冲
NSMutableData *writer = [[NSMutableData alloc] init];
//将字符串添加到缓冲中
// NSLog(@"[file dataUsingEncoding:NSUTF8StringEncoding]=%@",[file data UsingEncoding:NSUTF8StringEncoding]);
[writer appendData:[data dataUsingEncoding:NSUTF8StringEncoding]];
//将其他数据添加到缓冲中
//将缓冲的数据写入到文件中
[writer writeToFile:path atomically:YES];
}
/******文件读取******/
-(NSString *)readXml
{
//创建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//获取路径
//参数NSDocumentDirectory要获取那种路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径
//更改到待操作的目录下
[fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
//获取文件路径 文件名是cc.txt
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"cc.txt"];
NSData *reader = [NSData dataWithContentsOfFile:path];
return [[NSString alloc] initWithData:reader
encoding:NSUTF8StringEncoding];
}
原文地址:http://www.cnblogs.com/clumsy1006/p/3824349.html