注:大文件上傳或者下載,如果一次性加載數(shù)據(jù)到內(nèi)存,會(huì)導(dǎo)致內(nèi)存暴漲漩符,所以需要使用輸入輸出流,建立起文件和內(nèi)存中的管道驱还,通過管道輸入和輸出數(shù)據(jù)
文件輸入流NSInputStream
- 創(chuàng)建輸入流
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:filePath];
inputStream.delegate = self;
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[inputStream open];
- 文件數(shù)據(jù)讀取過程回調(diào)
- (void)stream:(NSInputStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventOpenCompleted: // 文件打開成功
NSLog(@"文件打開,準(zhǔn)備讀取數(shù)據(jù)");
break;
case NSStreamEventHasBytesAvailable: // 讀取到數(shù)據(jù)
{
uint8_t buf[1024];
NSInteger readLength = [stream read:buf maxLength:1024];
if (readLength > 0) {
[self.data appendBytes:(const void *)buf length:readLength];
}else {
NSLog(@"未讀取到數(shù)據(jù)");
}
break;
}
case NSStreamEventEndEncountered: // 文件讀取結(jié)束
{
NSLog(@"數(shù)據(jù)讀取結(jié)束");
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
stream = nil;
break;
}
default:
break;
}
}
文件輸出流NSOutputStream
- 創(chuàng)建輸出流
// 開啟文件輸出流
self.outputStream = [NSOutputStream outputStreamToFileAtPath:_tempPath append:YES];
[self.outputStream open];
- 數(shù)據(jù)流輸出
// 輸出數(shù)據(jù)
[self.outputStream write:data.bytes maxLength:data.length];
- 關(guān)閉數(shù)據(jù)流
[self.outputStream close];
self.outputStream = nil;