在 Objective C 中使用 NSStream 将 NSData 写入输出流所需的帮助
我使用以下代码将文件从路径写入输出流,但每次运行代码时,它总是根据我的文件大小(8MB 或 5MB 等)向流写入 131768 字节。有人可以帮我检查一下吗?我似乎找不到问题。或者还有其他方法可以做到吗?我使用 NSStream 并使用以下代码:
NSString *filesContent = [[NSString alloc] initWithContentsOfFile:myMediaFile]; // myMediaFile is a path to my file eg. .../Documents/myvideo.mp4/
NSData *data = [ filesContent dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
const uint8_t *buf = [data bytes];
NSUInteger length = [data length];
NSLog(@"datalen = %d",length);
NSInteger nwritten = [outputStream write:buf maxLength:length];
if (-1 == nwritten) {
NSLog(@"Error writing to stream %@: %@", outputStream, [outputStream streamError]);
}else{
NSLog(@"Wrote %ld bytes to stream %@.", (long long)nwritten, outputStream);
}
i using the following code which writes the file from a path to an output stream but every time i run the code, it always write 131768 bytes to the stream regards of my file size(8MB or 5MB or etc). Can someone please check for me? i can't seems to find the problem. Or it there other ways to do it? I'm using NSStream with the following code:
NSString *filesContent = [[NSString alloc] initWithContentsOfFile:myMediaFile]; // myMediaFile is a path to my file eg. .../Documents/myvideo.mp4/
NSData *data = [ filesContent dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
const uint8_t *buf = [data bytes];
NSUInteger length = [data length];
NSLog(@"datalen = %d",length);
NSInteger nwritten = [outputStream write:buf maxLength:length];
if (-1 == nwritten) {
NSLog(@"Error writing to stream %@: %@", outputStream, [outputStream streamError]);
}else{
NSLog(@"Wrote %ld bytes to stream %@.", (long long)nwritten, outputStream);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是How to use NSOutputStream's write message?的重复,不是我很惊讶你没有找到那个。
底线; write:maxLength: 方法不一定会一次性写入您传递给它的所有数据。由于涉及缓冲,因此您可能需要循环写入数据,因为输出流上有可用空间。
请注意,我所说的“循环”并不是指“民意调查”。
This is a duplicate of How to use NSOutputStream's write message?, not that I'm surprised you didn't find that one.
Bottom line; the
write:maxLength:
method isn't necessarily going to write all the data you pass to it all at once. There is buffering involved and, thus, you'll likely need to loop writing data as space is available on the output stream.Note that by "loop", I do not mean "poll".