NSInputStream读取文件

  1.         char *message = "I LOVE U";
  2.         NSInteger length = sizeof(char)*8;
  3.         NSData *data = [[NSData alloc] initWithBytes:message length:length];
  4.         NSInputStream *inputStream = [[NSInputStream alloc] initWithData:data];     
  5.         [inputStream open];
  6.         // read and dump to NSTextView
  7.         NSInteger maxLength = 128;
  8.         uint8_t readBuffer [maxLength];
  9.         BOOL endOfStreamReached = NO;
  10.         while (! endOfStreamReached)
  11.         {
  12.                 NSInteger bytesRead = [inputStream read: readBuffer maxLength:maxLength];
  13.                 if (bytesRead == 0)
  14.                 {
  15.                         endOfStreamReached = YES;
  16.                 } else if (bytesRead == -1)
  17.                 {
  18.                         endOfStreamReached = YES;
  19.                 } else
  20.                 {
  21.                         NSString *readBufferString = [[NSString alloc] initWithBytesNoCopy: readBuffer length: bytesRead encoding: NSUTF8StringEncoding freeWhenDone: NO];
  22.                         [self.textView setText:[[textView text] stringByAppendingString:readBufferString]];
  23.                         [readBufferString release];
  24.                 }
  25.         }
  26.         [inputStream close];
  27.         [inputStream release];

你可能感兴趣的:(NSInputStream读取文件)