分类:
常用代码
- -(void) write
- {
- //创建文件管理器
- NSFileManager *fileManager = [NSFileManager defaultManager];
- //获取路径
- //参数NSDocumentDirectory要获取那种路径
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径
- //更改到待操作的目录下
- [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
- //[fileManager removeItemAtPath:@"config" error:nil];//移除本文件管理器下的该项
- NSString *path = [documentsDirectory stringByAppendingPathComponent:@"config"];//获取文件路径
- //判断文件是否存在
- if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {//如果文件不存在则创建
- //创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil
- NSData *d_data=[[NSMutableDictionary alloc] init];
- [d_data setValue:@"" forKey:@"userid"];//手机号
- [d_data setValue:@"" forKey:@"pwd"];//密码
- [d_data setValue:@"0" forKey:@"backup"];//备份类型
- [fileManager createFileAtPath:path contents:d_data attributes:nil];
- NSString *str = @"a test file name";
- BOOL succeed = [str writeToFile: [documentsDirectory stringByAppendingPathComponent:@"test.xml"]
- atomically: YES
- encoding: NSUTF8StringEncoding
- error: nil];
- NSLog( @"succeed is %d", succeed ); // yes -> 写成功 no->写失败
- [d_data release];
- }
- }
- - (void)read
- {
- //读取数据
- NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath: @"test.xml"];
- NSData *data = [file readDataToEndOfFile];//得到xml文件 //读取到NSDate中
- NSString* aStr;
- aStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; //转换为NSString
- NSLog( @"aStr is %@", aStr );
- [file closeFile];
- }