iphone 读取 一行文件内容的两种方法

第一种:

 1 NSStringEncoding encoder = NSUTF8StringEncoding;
 2 
 3     NSString *file = [NSString stringWithContentsOfFile:@"/Users/bjimac/Desktop/528.edl" usedEncoding:&encoder
 4 
 5                                                   error:nil];
 6 
 7     NSRange line;
 8 
 9     line.location = 0;
10 
11     line.length = 1;
12 
13     
14 
15     int length = [file length];
16 
17  
18 
19     while (line.location <= length)
20 
21     {
22 
23         NSRange newLine = [file lineRangeForRange:line];
24 
25         NSString *content = [file substringWithRange:newLine];
26 
27         line.length = 1;
28 
29         line.location = newLine.location + newLine.length + 1;
30 
31     }
32 
33  
34 
35  - (NSString *)substringWithRange:(NSRange)aRange ----该函数会返回包含aRange的行
36 
37  

所以上面代码中content就得到每一行的内容了。

 

第二种:

 

读取一般性文档文件

 1 NSString *tmp;
 2 
 3         NSArray *lines; /*将文件转化为一行一行的*/
 4 
 5         lines = [[NSString    stringWithContentsOfFile:@"testFileReadLines.txt"] 
 6 
 7                        componentsSeparatedByString:@"\n"];
 8 
 9     
10 
11          NSEnumerator *nse = [lines objectEnumerator];
12 
13     
14 
15          // 读取<>里的内容
16 
17          while(tmp = [nse nextObject]) {
18 
19                   NSString *stringBetweenBrackets = nil;
20 
21                   NSScanner *scanner = [NSScanner scannerWithString:tmp];
22 
23                   [scanner scanUpToString:@"<" intoString:nil];
24 
25                   [scanner scanString:@"<" intoString:nil];
26 
27                   [scanner scanUpToString:@">" intoString:&stringBetweenBrackets];
28 
29                   NSLog([stringBetweenBrackets description]);
30 
31           }

 

posted @ 2012-05-14 11:35  妙笔  阅读(346)  评论(0编辑  收藏  举报