iOS NSStream 使用
简介
NSStream是一个基类,在Cocoa中它有两个子类NSInputStream和INOutputStream。分别对应输入和输出流。流提供了一种简单的方式在不同和介质中交换数据,这种交换方式是与设备无关的。你可以创建一个流通过NSData,File,SocketData,在处理大数据的时候,使用流就可以边读边处理。Cocoa中的流对象与Core Foundation中的流对象是对应的。我们可以通过toll-free桥接方法来进行相互转换。NSStream、NSInputStream和NSOutputStream分别对应CFStream、CFReadStream和CFWriteStream。但这两者间不是完全一样的。Core Foundation一般使用回调函数来处理数据。另外我们可以子类化NSStream、NSInputStream和NSOutputStream,来自定义一些属性和行为,而Core Foundation中的流对象则无法进行扩展。
类和方法介绍
- NSStream 基类
// 打开和关闭流 - (void)open; - (void)close;
//添加和移除RunLoop - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; - (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
- NSInputStream
//读取len长度的内容到buffer中 //返回值为读取的实际长度,所以最大为len - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len;
//读取当前流数据以及大小,注意buffer只在下一个流之前有效 - (BOOL)getBuffer:(uint8_t * __nullable * __nonnull)buffer length:(NSUInteger *)len;
- NSOutputStream
//把buffer中的数据写入流 //返回值实际写入的大小 - (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)len;
例子
大文件处理,TP
//初始化inputStream - (void)readStream:(NSString *)filePath { NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:filePath]; inputStream.delegate = self; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; } //初始化outputStream - (void)writeStream:(NSString *)filePath { NSOutputStream *writeStream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES]; [writeStream setDelegate:self]; [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [writeStream open]; }
//代理方法处理 - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { switch (eventCode) { case NSStreamEventHasBytesAvailable: { //读取 uint8_t buf[2048]; NSInteger len = 0; len = [(NSInputStream *)aStream read:buf maxLength:2048]; // 读取数据 if (len) { [data appendBytes:buf length:len]; } } break; case NSStreamEventEndEncountered: { [aStream close]; } break; case NSStreamEventHasSpaceAvailable: { //写入 NSInteger bufSize = 2048; uint8_t buf[bufSize]; [data getBytes:buf length:bufSize]; NSOutputStream *writeStream = (NSOutputStream *)aStream; NSInteger len = [writeStream write:buf maxLength:sizeof(buf)]; [data setLength:0]; self.location += len; if (self.location>self.fileSize) { [aStream close]; } } break; default: break; } }
mac快速生成大文件Python脚本。
import os for i in range(0,200): print i os.system("cat /usr/share/dict/words >>~/mkfile.test.txt") print "make file over !"