NSStream

NSStream (NSOutputStream、NSInput

2016-12-01  本文已影响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;

    }

}

上一篇下一篇

猜你喜欢

热点阅读