美文网首页
NSInputStream、NSOutputStream实现文件

NSInputStream、NSOutputStream实现文件

作者: wpLishuai | 来源:发表于2018-12-03 10:43 被阅读0次

    NSInputStream、NSOutputStream实现文件的拷贝

    NSString *inPath = @"/Users/yuanbinhuang/Documents/2.机器学习/(07)工作流程与模型调优/(7)工作流程与模型调优.avi";
        NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:inPath];
        inputStream.delegate = self;
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        [inputStream open];
        // 开始时间
        _startTime = CFAbsoluteTimeGetCurrent();
    
        NSString *toPath = @"/Users/yuanbinhuang/Desktop/video/aaa.avi";
        _outputStream = [[NSOutputStream alloc] initToFileAtPath:toPath append:YES];
        [_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        [_outputStream open];
    

    实现代理方法

    
    - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
        
        NSInputStream * input = nil;
        
        if ([aStream isKindOfClass:[NSInputStream class]]) {
            input = (NSInputStream *)aStream;
        }
        
        switch (eventCode) {
            case NSStreamEventHasBytesAvailable:
                {
                    long maxLen = 64 * 1024 * 8;
                    uint8_t streamData[maxLen];
                    
                    NSUInteger length = [input read:streamData maxLength:maxLen];
                    
                    if (length) {
                        NSData *data = [NSData dataWithBytes:streamData length:length];
                        NSLog(@"数据长度 --- %lu",(unsigned long)data.length);
                        [_outputStream write:data.bytes maxLength:maxLen];
                    } else {
                        NSLog(@"没有数据 -- %@",[NSDate date]);
                    }
                }
                break;
            case NSStreamEventErrorOccurred:{
                NSLog(@"进行异常处理");
            }
                break;
            case NSStreamEventEndEncountered: {
                //输入流关闭处理
                [input close];
                //从运行循环中移除
                [input removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
                //置为空
                input = nil;
                
                CFAbsoluteTime linkTime = (CFAbsoluteTimeGetCurrent() - _startTime);
                NSLog(@"Linked in %f ms", linkTime * 1000.0);
            }
                break;
            default:
                break;
        }
        
    }
    

    相关文章

      网友评论

          本文标题:NSInputStream、NSOutputStream实现文件

          本文链接:https://www.haomeiwen.com/subject/crnecqtx.html