NSOutputStream NSInputStream 简单用法



#import "ViewController.h"

@interface ViewController ()<NSStreamDelegate>

@property (nonatomic,strong) NSString *filePath;

@property (nonatomic,assign) int location;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createTestFile];
}

// 创建一个测试文件。

- (void)createTestFile{
    _filePath = NSHomeDirectory();
    _filePath = [_filePath stringByAppendingPathComponent:@"Documents/test_data.txt"];
    NSError *error;
    NSString *msg = @"测试数据,需要的测试数据,测试数据显示。";
    bool  isSuccess = [msg writeToFile:_filePath atomically:true encoding:NSUTF8StringEncoding error:&error];
    if (isSuccess) {
        NSLog(@"数据写入成功了");
    }else{
        NSLog(@"error is %@",error.description);
    }
    
    // 追加数据
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
    [handle seekToEndOfFile];
    NSString *newMsg = @".....我将添加到末尾你处";
    NSData *data = [newMsg dataUsingEncoding:NSUTF8StringEncoding];
    [handle writeData:data];
    [handle closeFile];
}



// NSOutPutStream 处理  写

- (IBAction)outPutStramAction:(id)sender {
    
    NSString *path = @"/Users/yubo/Desktop/stream_ios.txt";
    NSOutputStream *writeStream = [[NSOutputStream alloc]initToFileAtPath:path append:true];
    
    // 手动创建文件, 如果是系统创建的话, 格式编码不一样。
    bool flag = [@"Ios----->" writeToFile:path atomically:true encoding:NSUTF8StringEncoding error:nil];
    if (flag) {
        NSLog(@"创建成功");
    }
    
    writeStream.delegate = self;
    [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [writeStream open];
}


// NSInPutStream 处理   读

- (IBAction)inPutStreamAction:(id)sender {
    
    NSInputStream *readStream = [[NSInputStream alloc]initWithFileAtPath:_filePath];
    [readStream setDelegate:self];
    
    // 这个runLoop就相当于死循环,一直会对这个流进行操作。
    [readStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [readStream open];
}


#pragma mark  NSStreamDelegate代理 

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
    switch (eventCode) {
    
        case NSStreamEventHasSpaceAvailable:{ // 写
            
            NSString *content = [NSString stringWithContentsOfFile:_filePath encoding:NSUTF8StringEncoding error:nil];
            NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
            
            NSOutputStream *writeStream = (NSOutputStream *)aStream;
            [writeStream write:data.bytes maxLength:data.length];
            [aStream close];
            
            // 用buf的还没成功
            
//          [writeStream write:<#(nonnull const uint8_t *)#> maxLength:<#(NSUInteger)#>]; 乱码形式
            
            break;
        }
        case NSStreamEventHasBytesAvailable:{ // 读
                uint8_t buf[1024];
                NSInputStream *reads = (NSInputStream *)aStream;
                NSInteger blength = [reads read:buf maxLength:sizeof(buf)];
                if (blength != 0) {
                    NSData *data = [NSData dataWithBytes:(void *)buf length:blength];
                    NSString *msg = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                    NSLog(@"文件内容如下:----->%@",msg);
                }else{
                    [aStream close];
                }
                 break;
             }
        case NSStreamEventErrorOccurred:{// 错误处理
        
                NSLog(@"错误处理");
                break;
        
            }
        case NSStreamEventEndEncountered: {
               [aStream close];
               break;
           }
        case NSStreamEventNone:{// 无事件处理
        
                NSLog(@"无事件处理");
                break;
            }
        case  NSStreamEventOpenCompleted:{// 打开完成
            
                NSLog(@"打开文件");
                break;
            }
        default:
            break;
     }
}

@end


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值