有时我们在做读取文件操作时,可能直接将文件一次性读入内存中然后按行分割。这样对于较小的文件而言还好,但是当文件比较大的时候就不是那么理想了。所以我们可以采用惰性读取(lazily read)的方法,逐行读入文件,同时可以在后台处理每行数据,这样就不会影响用户操作了。使用NSInputStream就可以实现这样的功能。
一般来说,逐行读入文件需要以下几个步骤:
1、建立一个缓冲区,用来存储每次处理的数据
2、建立一个Stream对象,并用Stream读一块数据,存到缓冲区中
3、处理这一块数据,每发现一个换行符,就从缓冲区中把这一段数据(包括换行符)送出去处理。
4、在这一段数据中找不到换行符后,剩下的这一部分数据(如果有的话)仍然保存在缓冲区中。
5、回到2,重复这一过程直到文件读取完毕Stream对象关闭。
这里主角就是这个类啦
<span style="font-size:14px;">#import <Foundation/Foundation.h>
typedef void(^HandleBlock)(NSInteger lineNumber, NSString *line);
typedef void(^CompletionBlock)(NSInteger numberOfLines);
@interface CYZFileReader : NSObject
/**
* init a reader object using the URL of a file
*
* @param aFileURL a NSURL object to represent a file's URL
*
* @return a reader object
*/
- (id)initWithFileAtURL:(NSURL *)aFileURL;
/**
* init a reader object using the file's name.
* The file must be a local file.
*
* @param fileName local file's name
* @param extention the extention of file
*
* @return a reader object
*/
- (id)initWithLocalFileName:(NSString *)fileName withExtension:(NSString *)extention;
/**
* enumerate every line in file using a self-defined handle block and
* handle completion using a self-defined completion block
*
* @param block a block to enumerate every line and handle data
* @param completionBlock a block to handle completion event
*/
- (void)enumerateLinesUsingBlock:(HandleBlock)block completionBlock:(CompletionBlock) completionBlock;
@end</span><span style="font-size:18px;">
</span>