美文网首页NSStream
NSStream (NSOutputStream、NSInput

NSStream (NSOutputStream、NSInput

作者: 乐视薯片 | 来源:发表于2016-12-01 14:38 被阅读242次

    今天通过NSOutputStream、NSInputStream写了个小例子,将数据写入文件以及从文件中读,概念什么的就不再赘述,我直接贴一下代码:

    写入文件:

    static NSString*dataString =@"hello,world!!!!!!";

    static uint8_t*buff;

    - (void)writeToFile

    {

        outstream= [[NSOutputStream alloc]initToFileAtPath:_filePath append:YES];

        [outstream setDelegate:self];

        [outstream scheduleInRunLoop:[NSRunLoopcurrentRunLoop]forMode:NSDefaultRunLoopMode]; 

        [outstreamopen];

    }

    从文件中读:

    - (void)readFromFile

    {

        instream= [[NSInputStreamalloc]initWithFileAtPath:_filePath];

        [instream setDelegate:self];

        [instream scheduleInRunLoop:[NSRunLoopcurrentRunLoop]forMode:NSDefaultRunLoopMode];

        [instreamopen];

    }

    输入输出流代理实现(这个完全可以不用,可以直接使用writemaxLength以及readmaxLength实现文件的读写),这里只是练一下。

    - (void)stream:(NSStream*)aStream handleEvent:(NSStreamEvent)eventCode

    {

        NSData*data = [data StringdataUsingEncoding:NSUTF8StringEncoding];

        switch(eventCode) {

        case NSStreamEventHasSpaceAvailable:

        {

           uint8_t*dataBytes = (uint8_t*)[databytes];

           NSInteger dataLength = [datalength];

           NSInteger writeBytes;

           static NSIntegerwholeWriteBytes =0;

           if(wholeWriteBytes)

           {

              writeBytes = [(NSOutputStream*)aStreamwrite:dataBytesmaxLength:dataLength];

              wholeWriteBytes = wholeWriteBytes + writeBytes;

           }

        }

        break;

        case NSStreamEventHasBytesAvailable:

        {

           buff= (uint8_t*)malloc(1024);

           memset(buff,0,1024);

           NSInteger readBytes = [(NSInputStream*)aStreamread:buffmaxLength:17];

           NSLog(@"%ld",(long)readBytes);

           NSLog(@"%s",buff);

           buff=buff+ readBytes;

        }

         break;

        default:

         break;

        }

    }

    相关文章

      网友评论

        本文标题:NSStream (NSOutputStream、NSInput

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