1.NSInputStream文件的讀取流,是將本地的文件讀取到內(nèi)存中去
@property(nonatomic)NSInputStream*inputStream;
// ①文件讀取流的開啟 ?path為需要被讀取的文件路徑 ?
self.inputStream= [[NSInputStreamalloc]initWithFileAtPath:path];
[self.inputStreamsetDelegate:self];
[self.inputStreamscheduleInRunLoop:[NSRunLoopcurrentRunLoop]forMode:NSDefaultRunLoopMode];
[self.inputStreamopen];
// ②在開啟了文件流以后就會(huì)在代理方法中執(zhí)行讀取操作
#define HBUFC_BUFFER_SIZE1024 ?//一次最大讀取的字節(jié)
uint8_thbufc_file_buffer[HBUFC_BUFFER_SIZE]; // 一個(gè)緩存的數(shù)組
-(void)stream:(NSStream*)stream handleEvent:(NSStreamEvent)eventCode{
switch(eventCode) {
// 有有效讀取字節(jié)的時(shí)候進(jìn)入這個(gè)case,一次性將所有的流進(jìn)入
caseNSStreamEventHasBytesAvailable:{
// 將HBUFC_BUFFER_SIZE 大小的字節(jié)流放入到緩存數(shù)組hbufc_file_buffer中
longbytes = [(NSInputStream*)streamread:hbufc_file_buffermaxLength:HBUFC_BUFFER_SIZE];
// 進(jìn)行循環(huán)的讀取,注意每次data取的是讀取到的字節(jié)數(shù) 而不是最大字節(jié)數(shù)即bytes
while(bytes >0) {
NSData*data = [NSDatadataWithBytes:hbufc_file_bufferlength:bytes];
[self.dataappendData:data];
bytes = [(NSInputStream*)streamread:hbufc_file_buffermaxLength:HBUFC_BUFFER_SIZE];
}
}
break;
// 流讀取完畢后,進(jìn)入這個(gè)case 將流關(guān)閉妄田,并且從runloop中移除
caseNSStreamEventEndEncountered:{
NSString*dataStr = [[NSStringalloc]initWithData:self.dataencoding:(NSUTF8StringEncoding)];
NSLog(@"%@===",dataStr);
[streamclose];
[streamremoveFromRunLoop:[NSRunLoopcurrentRunLoop]forMode:NSDefaultRunLoopMode];
stream =nil;
}
break;
default:
break;
}