//讀取文件內容操作- (void) loadFileContentsIntoTextView{
//通過流打開一個文件
NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath: filePath];
[inputStream open];
NSInteger maxLength = 128;
uint8_t readBuffer [maxLength];
//是否已經到結尾標識
BOOL endOfStreamReached = NO;
// NOTE: this tight loop will block until stream ends
while (! endOfStreamReached)
{
NSInteger bytesRead = [inputStream read: readBuffer maxLength:maxLength];
if (bytesRead == 0)
{//文件讀取到最後
endOfStreamReached = YES;
}
else if (bytesRead == -1)
{//文件讀取錯誤
endOfStreamReached = YES;
}
else
{
NSString *readBufferString =[[NSString alloc] initWithBytesNoCopy: readBuffer length: bytesRead encoding: NSUTF8StringEncoding freeWhenDone: NO];
//將字符不斷的加載到視圖
[self appendTextToView: readBufferString];
[readBufferString release];
}
}
[inputStream close];
[inputStream release];
}
異步文件的讀取 ,在網絡方面,由於網絡的不可靠性可能會造成NSFileManager的文件操作方法的阻塞,而以流的方式進行操作則可以實現異步的讀取。NSStream是可以異步工作的。可以注冊一個在流中有字節可讀的時候回調的函數,如果沒有可讀的,就不要阻塞住,回調出去。