【转】iphone 输入/输出流异步读写数据
1、首先是往文件里写入数据
WriteFile.h
- #import <Foundation/Foundation.h>
- #import <UIKit/UIKit.h>
- @class NoteDb;
- @interface WriteFile : NSObject<NSStreamDelegate>{
- //文件地址
- NSString *parentDirectoryPath;
- //输出流,写数据
- NSOutputStream *asyncOutputStream;
- //写数据的内容
- NSData *outputData;
- //位置及长度
- NSRange outputRange;
- //数据的来源
- NoteDb *aNoteDb;
- }
- @property (nonatomic,retain) NSData *outputData;
- @property (nonatomic,retain) NoteDb *aNoteDb;
- //写数据
- -(void)write;
- @end
实现文件WriteFile.m
- #import "WriteFile.h"
- #import "NoteDb.h"
- @implementation WriteFile
- @synthesize outputData,aNoteDb;
- -(id)init{
- self=[super init];
- if (!self) {
- [self release];
- return nil;
- }
- outputData=[[NSData alloc]init];
- aNoteDb=[[NoteDb alloc]init];
- return self;
- }
- -(void)write{
- //NSLog(@"%@",self.aNoteDb);
- //沙盒路径
- NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentsDirectory = [paths objectAtIndex:0];
- //文件名字是note.txt
- NSString *path = [documentsDirectory stringByAppendingPathComponent:@"note.txt"];
- [asyncOutputStream release];
- parentDirectoryPath = path;
- //数据源
- NSData *tmpdata = [NSKeyedArchiver archivedDataWithRootObject:self.aNoteDb.noteList];
- //self.outputData=[[NSData alloc]initWithData:tmpdata];
- self.outputData=tmpdata;
- //位置从哪开始
- outputRange.location=0;
- //创建文件
- [[NSFileManager defaultManager] createFileAtPath:parentDirectoryPath
- contents:nil attributes:nil];
- //初始化输出流
- asyncOutputStream = [[NSOutputStream alloc] initToFileAtPath: parentDirectoryPath append: NO];
- //回调方法,
- [asyncOutputStream setDelegate: self];
- //异步处理,
- [asyncOutputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
- //打开异步输出流
- [asyncOutputStream open];
- }
- -(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent{
- // NSLog(@"as");
- NSOutputStream *outputStream = (NSOutputStream*) theStream;
- BOOL shouldClose = NO;
- switch (streamEvent)
- {
- case NSStreamEventHasSpaceAvailable://读事件
- {
- //缓冲区
- uint8_t outputBuf [1];
- //长度
- outputRange.length = 1;
- //把数据放到缓冲区中
- [outputData getBytes:&outputBuf range:outputRange];
- //把缓冲区中的东西放到输出流
- [outputStream write: outputBuf maxLength: 1];
- //判断data数据是否读完
- if (++outputRange.location == [outputData length])
- {
- shouldClose = YES;
- }
- break;
- }
- case NSStreamEventErrorOccurred:
- {
- //出错的时候
- NSError *error = [theStream streamError];
- if (error != NULL)
- {
- UIAlertView *errorAlert = [[UIAlertView alloc]
- initWithTitle: [error localizedDescription]
- message: [error localizedFailureReason]
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [errorAlert show];
- [errorAlert release];
- }
- shouldClose = YES;
- break;
- }
- case NSStreamEventEndEncountered:
- shouldClose = YES;
- }
- if (shouldClose)
- {
- //当出错或者写完数据,把线程移除
- [outputStream removeFromRunLoop: [NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
- //最后关掉输出流
- [theStream close];
- }
- }
- -(void)dealloc{
- [outputData release];
- [aNoteDb release];
- [super dealloc];
- }
- @end
2、其次是从文件里读出数据
ReadFile.h
- #import <Foundation/Foundation.h>
- @class NoteDb;
- @interface ReadFile : NSObject<NSStreamDelegate>{
- //路径
- NSString *parentDirectoryPath;
- //异步输出流
- NSInputStream *asyncInputStream;
- //读出来的数据
- NSMutableData *resultData;
- //返回去的数据
- NoteDb *aNoteDb;
- }
- @property(nonatomic,retain)NoteDb *aNoteDb;
- @property (nonatomic, retain) NSMutableData *resultData;
- //开始读数据
- -(void)read;
- //读出来的数据追加到resultData上
- - (void)appendData:(NSData*)_data;
- //
- - (void)dataAtNoteDB;
- //返回去的数据
- - (NoteDb*)getNoteDb;
- @end
实现文件ReadFile.m
- #import "ReadFile.h"
- #import "NoteDb.h"
- #import "NoteList.h"
- #import "WriteFile.h"
- @implementation ReadFile
- @synthesize aNoteDb,resultData;
- -(id)init{
- self=[super init];
- //aNoteDb=[[NoteDb alloc]init];
- resultData=[[NSMutableData alloc]init];
- return self;
- }
- -(void)read{
- //沙盒路径
- NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentsDirectory = [paths objectAtIndex:0];
- //文件名
- NSString *path = [documentsDirectory stringByAppendingPathComponent:@"note.txt"];
- /*
- if(![[NSFileManager defaultManager]fileExistsAtPath:path]){
- //如果不存在,就新建
- WriteFile *file=[[WriteFile alloc]init];
- [file write];
- [file release];
- }else{
- NSLog(@"有note.txt文件");
- }
- */
- [asyncInputStream release];
- parentDirectoryPath = path;
- //异步输入流初始化,并把赋于地址
- asyncInputStream =
- [[NSInputStream alloc] initWithFileAtPath: parentDirectoryPath];
- //设置代理(回调方法、委托)
- [asyncInputStream setDelegate: self];
- //设置线程,添加线程,创建线程:Runloop顾名思义就是一个不停的循环,不断的去check输入
- [asyncInputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
- forMode:NSDefaultRunLoopMode];
- //打开线程
- [asyncInputStream open];
- }
- //追加数据
- - (void)appendData:(NSData*)_data{
- [resultData appendData:_data];
- }
- //回调方法,不停的执行
- -(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent{
- BOOL shouldClose = NO;
- NSInputStream *inputStream = (NSInputStream*) theStream;
- //NSLog(@"as");
- switch (streamEvent)
- {
- case NSStreamEventHasBytesAvailable:
- {
- //读数据
- //读取的字节长度
- NSInteger maxLength = 128;
- //缓冲区
- uint8_t readBuffer [maxLength];
- //从输出流中读取数据,读到缓冲区中
- NSInteger bytesRead = [inputStream read: readBuffer
- maxLength:maxLength];
- //如果长度大于0就追加数据
- if (bytesRead > 0)
- {
- //把缓冲区中的数据读成data数据
- NSData *bufferData = [[NSData alloc]
- initWithBytesNoCopy:readBuffer
- length:bytesRead
- freeWhenDone:NO];
- //追加数据
- [self appendData:bufferData];
- //release掉data
- [bufferData release];
- }
- break;
- }
- case NSStreamEventErrorOccurred:
- {
- //读的时候出错了
- NSError *error = [theStream streamError];
- if (error != NULL)
- {
- UIAlertView *errorAlert = [[UIAlertView alloc]
- initWithTitle: [error localizedDescription]
- message: [error localizedFailureReason]
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [errorAlert show];
- [errorAlert release];
- }
- shouldClose = YES;
- break;
- }
- case NSStreamEventEndEncountered:
- {
- shouldClose = YES;
- //数据读完就返回数据
- [self dataAtNoteDB];
- [theStream close];
- }break;
- }
- if (shouldClose)
- {
- //当文件读完或者是读到出错时,把线程移除
- [inputStream removeFromRunLoop: [NSRunLoop currentRunLoop]
- forMode:NSDefaultRunLoopMode];
- //并关闭流
- [theStream close];
- }
- }
- -(void) dataAtNoteDB{
- aNoteDb=nil;
- aNoteDb=[[NoteDb alloc]init];
- aNoteDb.noteList = [NSKeyedUnarchiver unarchiveObjectWithData:resultData];
- //NSLog(@"%@",aNoteDb);
- /*
- for (id tmp in aNoteDb.noteList.noteArray)
- {
- NSLog(@"tmp = %@",tmp);
- }
- */
- }
- - (NoteDb*)getNoteDb{
- return self.aNoteDb;
- }
- -(void)dealloc{
- [aNoteDb release];
- [resultData release];
- [super dealloc];
- }
- @end
【转】iphone 输入/输出流异步读写数据的更多相关文章
- C++学习笔记10_输入输出流.文件读写
//从键盘输入到程序,叫标准input:从程序输出到显示器,叫标准output:一并叫标准I/O //文件的输入和输出,叫文件I/O cout<<"hellow word&quo ...
- Java基础知识强化之IO流笔记57:数据输入输出流(操作基本数据类型)
1. 数据输入输出流(操作基本数据类型) (1)数据输入流:DataInputStream DataInputStream(InputStream in) (2)数据输出流:DataOutputStr ...
- 序列流、对象操作流、打印流、标准输入输出流、随机访问流、数据输入输出流、Properties(二十二)
1.序列流 * 1.什么是序列流 * 序列流可以把多个字节输入流整合成一个, 从序列流中读取数据时, 将从被整合的第一个流开始读, 读完一个之后继续读第二个, 以此类推.* 2.使用方式 * 整合两个 ...
- 4、BufferedIn(out)putStream--->字节输入/输出流的缓冲区类(高效类:高效率读写)
前言 字节流一次读写一个数组的速度明显比一次读写一个字节的速度快很多,这是加入了数组这样的缓冲区效果,java本身在设计的时候,也考虑到了这样的设计思想(装饰设计模式后面讲解),所以提供了字节缓冲区流 ...
- C++ 输入输出流 文本文件 二进制文件读写
文本文件/ASCII文件(能直接显示内容,费存储空间):文件中每一个字节中均以ASCII代码形式存放数据,即一个字节存放一个字符,这个文件就是ASCII文件或称字符文件. 二进制文件(不能显示内容,节 ...
- DataInputStream 数据类型数据输入输出流
package IOliu; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileI ...
- java.IO输入输出流:过滤流:buffer流和data流
java.io使用了适配器模式装饰模式等设计模式来解决字符流的套接和输入输出问题. 字节流只能一次处理一个字节,为了更方便的操作数据,便加入了套接流. 问题引入:缓冲流为什么比普通的文件字节流效率高? ...
- Java中IO流,输入输出流概述与总结
总结的很粗糙,以后时间富裕了好好修改一下. 1:Java语言定义了许多类专门负责各种方式的输入或者输出,这些类都被放在java.io包中.其中, 所有输入流类都是抽象类InputStream(字节输入 ...
- JAVA输入输出流
概述: 各种流类型(类和抽象类)都位于位于java.io包中,各种流都分别继承一下四种抽象流中的一种: 类型 字节流 字符流 输入流 InputStream Reader 输出流 OutputStre ...
随机推荐
- [PY3]——时间处理——datetime | calendar
Python3的日期/时间处理模块 datetime的格式化符号 格式化符号 表示 %y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %m 月份(01-12) %d 日 ...
- table 中的tr 行点击 变换颜色背景
<style> table{border-collapse: collapse;border-spacing: 0; width: 100%;} table tr th,td{border ...
- Hadoop学习笔记(10) ——搭建源码学习环境
Hadoop学习笔记(10) ——搭建源码学习环境 上一章中,我们对整个hadoop的目录及源码目录有了一个初步的了解,接下来计划深入学习一下这头神象作品了.但是看代码用什么,难不成gedit?,单步 ...
- 1.Java设计模式-工厂模式
1.简单工厂模式(Factory Method) 常用的工厂模式是静态工厂模式,利用static修饰方法,作为一种类似于常见的工具类Utils等辅助效果,一般情况下工厂类不需要实例化. //1.定义一 ...
- Excel2010条件格式的位置
以下是excel2010的条件格式设置方法(英文版) 具体使用方法可以参考 http://office.microsoft.com/zh-cn/excel-help/HA102809768.aspx
- JQuery实现获取多个input输入框的值,并存放在一个数组中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Luogu4887 第十四分块(前体)
sto \(lxl\) orz 考虑莫队,每次移动端点,我们都要询问区间内和当前数字异或有 \(k\) 个 \(1\) 的数字个数 询问 \([l,r]\) 可以再次离线,拆成询问 \([1,l-1] ...
- gulp & webpack整合
为什么需要前端工程化? 前端工程化的意义在于让前端这个行业由野蛮时代进化为正规军时代,近年来很多相关的工具和概念诞生.好奇心日报在进行前端工程化的过程中,主要的挑战在于解决如下问题:✦ 如何管理多个项 ...
- 从零开始安装、编译、部署 Docker
简介 主要介绍如何从基础系统debian部署docker关于docker基础知识在 相关资料 里有链接 安装docker 1.使用root用户身份添加apt源添加public key使docker的安 ...
- error C3861: “getpid”: 找不到标识符
原文:http://blog.csdn.net/woniu199166/article/details/52471242 这种错误一般就是没有对应的函数或者对应的头文件 旧版的vs添加#include ...