http://www.cnblogs.com/jiangyuxuan/archive/2013/03/09/2950988.html
OneSecWriteData.h// appendDate Created by 英海 王 on 13-1-7.// Copyright (c) 2013年 __MyCompanyName__. All rights reserved.//#import <Foundation/Foundation.h>@interface OneSecWriteData : NSObject{@private //程序执行Home目录 NSString *_homePath; //文件所在目录 NSString *_filePath; }@property (nonatomic,copy) NSString *homePath;@property (nonatomic,copy) NSString *filePath;@property (nonatomic,assign) BOOL isSuccess; //表示文件是否创建成功 assign是可以直接赋值的意思-(BOOL)CreateFile;-(void)WriteData;@end
OneSecWriteData.m// appendDate Created by 英海 王 on 13-1-7.// Copyright (c) 2013年 __MyCompanyName__. All rights reserved.//#import "OneSecWriteData.h"
@implementation OneSecWriteData
@synthesize homePath=_homePath;
@synthesize filePath=_filePath;
@synthesize isSuccess=_isSuccess;
//创建文件-(BOOL)CreateFile
{
self.homePath=NSHomeDirectory(); //获取当前程序执行的home目录
self.filePath =[self.homePath stringByAppendingPathComponent:@"Desktop/Date.text"];
//获取文件所在的目录
NSFileManager *fileManger=[NSFileManager defaultManager];
//如果路径不存在则创建
if(![fileManger fileExistsAtPath:self.filePath])
{
self.isSuccess=[fileManger createFileAtPath:self.filePath contents:nil attributes:nil];
}
if(self.isSuccess)
{
NSLog(@"文件创建成功!");
} return self.isSuccess;
}
//启动写入数据的定时器
-(void)WriteData{
//计划1秒一次, 目标是self,方法是空的 用户信息空 最后表示定时器重复调用
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(StartWriteData:) userInfo:nil repeats:YES];
//此出执行完毕会返回一个NSTimer类型的值 我们在以下方法中一timer这个参数来接收值
}
//开始写入数据
-(void)StartWriteData:(NSTimer *)timer{
//取文件所在的目录
NSFileHandle *fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:self.filePath];
//追加数据 [fileHandle seekToEndOfFile]; //跳到文件末尾
//[fileHandle seekToFileOffset:10]; //从某个字符后开始追加写入内容, 在写入内容时会覆盖掉原有数据 // 获取系统当前时间
NSDate * date = [NSDate date];
NSTimeInterval sec = [date timeIntervalSinceNow];
NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec]; //设置时间输出格式:
NSDateFormatter * df = [[NSDateFormatter alloc] init ];
[df setDateFormat:@"当前系统时间为:yyyy/MM/dd HH:mm:ss\n"];
NSString * na = [df stringFromDate:currentDate]; NSLog(@"系统当前时间为:%@",na);
NSString *str= na; //写入的内容
NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:data]; //写入
[fileHandle closeFile]; //关闭写入流
/*********今日习题**********/ // 1.熟练掌握课堂的所举的实例 // 2.创建一个Date.text文件。获取当前的日期,将日期格式为"2013/01/07 14:13:22"的形式。 // 然后一秒钟记录一次,将新的时间存入到文件中。 // 3.复制一个大型文件,为了节约内存,每次只读取500个字节。 OneSecWriteData *oneSecWriteData=[[OneSecWriteData alloc]init]; //初始化 [oneSecWriteData CreateFile]; //创建文件 [oneSecWriteData WriteData]; //写入数据 //获取系统时间 NSDate *date=[NSDate date]; [[NSRunLoop currentRunLoop] runUntilDate:[date dateByAddingTimeInterval:5]]; //共执行5次