文件定时读取(即用定时器读取NSTime)注意定时器一般在一个类里面设置
// // WriteData.m // FileMangerTask1 // // Created by ganchaobo on 13-5-4. // Copyright (c) 2013年 ganchaobo. All rights reserved. // #import "WriteData.h" @interface WriteData() -(void)startwrite:(NSTimer *) time; @end @implementation WriteData -(void)Runwrite{ //创建目录 NSFileManager *fileManager=[NSFileManager defaultManager]; BOOL isscuess= [fileManager createFileAtPath:@"/Users/ganchaobo/Desktop/1.text" contents:nil attributes:nil]; if(isscuess){ NSLog(@"create success"); } NSFileHandle *filehandle=[NSFileHandle fileHandleForUpdatingAtPath:@"/Users/ganchaobo/Desktop/1.text"]; [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startwrite:) userInfo:filehandle repeats:YES]; } -(void)startwrite:(NSTimer *) time{ NSFileHandle * handle=[time userInfo]; static int count=0; [handle seekToEndOfFile]; //对内容的描述 NSDate *date=[NSDate date]; NSDateFormatter *formatter=[[[NSDateFormatter alloc] init] autorelease]; formatter.dateFormat=@"yyyy-MM-dd hh:mm:ss"; NSString *str= [formatter stringFromDate:date]; str=[str stringByAppendingString:@"\n"]; NSData *date1=[str dataUsingEncoding:NSUTF8StringEncoding] ; [handle writeData:date1]; if(count==10){ [time invalidate] ; [handle closeFile]; } count++; } @end
拷贝一个大文件 以500字节进行分段读取
void copybigfile(){ NSString *newpath=@"/Users/ganchaobo/Desktop/1_bar.rar"; NSString *orginpath=@"/Users/ganchaobo/Desktop/1.rar"; NSFileManager *filemanger=[NSFileManager defaultManager]; BOOL issuccess=[filemanger createFileAtPath:newpath contents:nil attributes:nil]; if(issuccess){ NSLog(@"create success"); } NSFileHandle *orginhandle=[NSFileHandle fileHandleForReadingAtPath:orginpath]; NSFileHandle *newhandle=[NSFileHandle fileHandleForWritingAtPath:newpath]; //要算出文件的大小 NSError *error=nil; NSDictionary *dic= [filemanger attributesOfItemAtPath:orginpath error:&error]; if(error){ NSLog(@"read file size filder"); } NSNumber * filesize=[dic objectForKey:NSFileSize]; NSInteger * longsize=[filesize longValue];//文件的大小 BOOL isEnd=YES; NSData *date=nil; NSInteger readsize=0; while (isEnd) { if(longsize-readsize<500){ date=[orginhandle readDataOfLength:readsize]; isEnd=NO; } else{ date=[orginhandle readDataOfLength:500]; } readsize=readsize+500; [newhandle writeData:date]; } [newhandle closeFile]; [orginhandle closeFile]; }
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。