加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

SQLite - 文件的基本操作

(2013-04-23 10:02:45)
标签:

sqlite

文件读写

it

分类: Mac/IOS那些事
1.流程 :
是读取文件 然后把数据以string的格式写入的txt文件中 新建正则表达式 用正则匹配出想要的数据
2.Demo
#import <Foundation/Foundation.h>
#import "FMDatabase.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSFileManager *fm = [NSFileManager defaultManager];
        NSStringEncoding encoding = NSUTF8StringEncoding;
        NSString *filePath = @"/Users/loveuu/Documents/text2.txt"; 没有会自动创建
        NSString *insertStr =@"id = 20090502137, name = Jack, socre1 = 89.00, score2 = 80.50, socre3 = 80.00 id = 20090502137, name = Jack, score1 = 89.00, score2 = 80.50, score3 = 80.00 id = 20090502138, name = Jack, score1 = 89.00, score2 = 80.50, score3 = 80.00 id = 20090502139, name = Jack, score1 = 89.00, score2 = 80.50, score3 = 80.00  id = 20090502140, name = Jack, score1 = 89.00, score2 = 80.50, score3 = 100.00";
        //如果没有改文件就创建
        if([fm createFileAtPath:filePath contents:nil attributes:nil])
        {
            NSData *data = [insertStr dataUsingEncoding:encoding];
            [data writeToFile:filePath atomically:YES];
        }
        //拿到文件读取数据
        NSString *getFileContent = [[NSString alloc]initWithContentsOfFile:filePath
        encoding:encoding error:nil];
        //NSLog(@"%@",getFileContent);
       //正则string
        NSString *pattern  = @"id = (\\w+), name = (\\w+), score1 = (\\d+.\\d+), score2 = (\\d+.\\d+), score3 = (\\d+.\\d+)";
        //正则string格式化为regex
        NSError *error = nil;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
        options:0 error:&error];
       //匹配出的放入数组
        NSArray *matches= [regex matchesInString:getFileContent options:0 range:NSMakeRange(0,
        [getFileContent length])];
        for (NSTextCheckingResult *match in matches) {
            NSRange firstRange = [match rangeAtIndex:0];
            NSRange secondRange = [match rangeAtIndex:2];
            NSString *id = [getFileContent substringWithRange:firstRange];
            NSString *name = [getFileContent substringWithRange:secondRange];
            NSLog(@"id=%@,name=%@",id,name);
        }
    }
    return 0;
}
ouput: //输出的是符合匹配结果的
 id=id = 20090502137, name = Jack, score1 = 89.00, score2 = 80.50, score3 = 80.00,name=Jack
 id=id = 20090502138, name = Jack, score1 = 89.00, score2 = 80.50, score3 = 80.00,name=Jack
 id=id = 20090502139, name = Jack, score1 = 89.00, score2 = 80.50, score3 = 80.00,name=Jack
 id=id = 20090502140, name = Jack, score1 = 89.00, score2 = 80.50, score3 = 100.00,name=Jack

src://http://blog.sina.com.cn/s/blog_63a4502101015avy.html

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有